Notifications = require 'app/collections/notifications'


play = require 'audio-play'
require './app.styl'
require './header/header.coffee'
require './sidenav/sidenav.coffee'

vision = angular.module('vision')

vision.config ($stateProvider) ->
  'ngInject'
  $stateProvider.state 'app',
    url: '/', template: '<app />'
    module: yes, title: 'Vision'

vision.component 'app',
  template: do require './app.jade'
  controllerAs: 'vm'
  controller: ($vision, $scope, $mdToast) ->
    $vision.attach(module, $scope); vm = @
    'ngInject'


    @notifs = []


    @load = yes
    @subscribe './server', 'notifications', null, =>
      setTimeout =>
        @notifReady = yes
      , 1000
    @helpers
      notif: -> Notifications.find {}, transform: (doc) =>
        if @notifReady
          unless doc._id in @notifs
            @showNotif doc
        unless doc._id in @notifs
          @notifs.push doc._id
        return doc

    @audios = {}
    @play = (audio) ->
      audio = @audios[audio] ?= play("audio/#{audio}")
      do audio.play

    @showNotif = (doc) =>

      if doc.audio
        @play doc.audio


      doc.time ?= 5000
      if doc.href
        href = "href='#{doc.href}'"
      else href = ''
      toast = $mdToast.show
        autoWrap: yes
        position: 'top right'
        hideDelay: doc.time
        template: """
          <md-toast ng-click='click()'>#{doc.message}</md-toast>
        """
        controller: ($scope, $location, $state, $mdToast) ->
          'ngInject'
          $scope.click = ->
            return null unless doc.href?
            if doc.href.charAt(0) is '/'
              $location.path doc.href.substr 1
            else if doc.href.charAt(0) is '#'
              $location.hash doc.href.substr 1
            else return null
            $mdToast.hide toast



    return
