_ = require 'lodash'
path = require 'path'

vision = angular.module 'vision'
vision.config ($stateProvider, $urlRouterProvider, $locationProvider) ->
  'ngInject'

  $urlRouterProvider.otherwise('/')

  $locationProvider.html5Mode
    enabled: true
    requireBase: false




vision.run ($state, $rootScope, $timeout, $mdSidenav, $vision) ->
  'ngInject'

  STATES = []

  $state.on = (param, cb) ->


  # для авторизации
  $rootScope.$on "$stateChangeStart", (event, toState, toParams, fromState, fromParams) ->

    # console.log toParams

    if toState.name is fromState.name

      try
        for key, val of toParams when toParams[key] isnt fromParams[key]
          cb(toParams) for cb in $vision.states[toState.name][key]

      # console.log JSON.stringify fromParams, null, 2
      # console.log JSON.stringify toParams, null, 2
      $state.go toState.name, toParams, notify: false
      do event.preventDefault
      return no

    # console.log toState.name, fromState.name

    $vision.title = toState.title if toState.title?

    # если публичный
    if toState.public
      return yes

    # если не публичный - проверяем доступ
    else if Meteor.userId()
      if toState.url is '/'
        $vision.title = toState.title if toState.title?
        return yes
      else if toState.module.access()
        $vision.title = toState.title if toState.title?
        return yes
      else return no


    # если не авторизован - отправляем на авторизацию
    else
      event.preventDefault()
      $state.go('login')
