 # Navigation bar controller
 # ---------------------------------------------------------------------------
 
-NavbarCtrl = ($scope, $rootScope, pwgAjax) ->
+NavbarCtrl = ($scope, pwgAjax) ->
   $scope.logout = () ->
     # NOTE: See https://groups.google.com/forum/#!msg/angular/bsTbZ86WAY4/gdpKwc4f7ToJ
     #

    s? and s.trim().length > 0

pwguardApp.controller 'LoginCtrl', ['$scope',
                                    '$rootScope',
                                    'pwgAjax',
                                    'pwgFlash',
                                    LoginCtrl]

# Main controller
# ---------------------------------------------------------------------------


MainCtrl = ($scope, $routeSegment, $location, pwgTimeout, pwgAjax, pwgFlash, macModal, $q) ->

  $scope.dialogConfirmTitle   = null
  $scope.dialogConfirmMessage = null

  $scope.loggedInUser  = null
  $scope.$routeSegment = $routeSegment
  $scope.segmentOnLoad = window.segmentForURL($location.path())
  $scope.initializing  = true

  pwgFlash.init() # initialize the flash service

  $scope.$on '$routeChangeSuccess', ->
    # Clear flash messages on route change.
    pwgFlash.clear 'all'

  # Page-handling.

  # Convenient way to show a page/segment

  $scope.redirectToSegment = (segment) ->
    url = $scope.pathForSegment segment
    if url?
      #console.log "Redirecting to #{url}"
      $location.path(url)
    else
      console.log "(BUG) No URL for segment #{segment}"

  $scope.segmentIsActive = (segment) ->
    ($routeSegment.name is segment) or ($routeSegment.startsWith("#{segment}."))

  $scope.pathForSegment = window.pathForSegment
  $scope.hrefForSegment = window.hrefForSegment

  $scope.loggedIn = ->
    $scope.loggedInUser?

  $scope.saveLoggedInUser = (user) ->
    $scope.loggedInUser =
      email:       user.email
      isAdmin:     user.admin
      displayName: user.displayName
      firstName:   user.firstName
      lastName:    user.lastName
      isMobile:    user.isMobile

  # On initial load or reload, we need to determine whether the user is
  # still logged in, since a reload clears everything in the browser.

  $scope.redirectIfNotLoggedIn

  validateLocationChange = (segment) ->
    useSegment = null
    if $scope.loggedInUser?
      # Ensure that the segment is valid for a logged in user.
      useSegment = 'search' # default
      if segment?
        if window.isPostLoginSegment(segment)
          if $scope.loggedInUser.isAdmin
            # Admins can go anywhere.
            useSegment = segment
          else if (not window.isAdminOnlySegment(segment))
            # Non-admins can go to non-admin segments.
            useSegment = segment

    else
      # Ensure that the segment is valid for a non-logged in user.
      if segment? and window.isPreLoginSegment(segment)
        useSegment = segment
      else
        useSegment = 'login'

    useSegment

  $scope.$on '$locationChangeStart', (e) ->
    segment = window.segmentForURL $location.path()
    useSegment = validateLocationChange segment
    if useSegment isnt segment
      e.preventDefault()
      $scope.redirectToSegment useSegment


  onSuccess = (response) ->
    $scope.initializing = false
    initialSegment = $scope.segmentOnLoad
    if response.loggedIn
      $scope.loggedInUser = response.user

    else
      $scope.loggedInUser = null

    useSegment = validateLocationChange initialSegment
    $scope.redirectToSegment useSegment

  onFailure = (response) ->
    $scope.initializing = false
    $scope.loggedInUser = null
    $scope.redirectToSegment("login")

  checkUser = ->
    url = $("#config").data("logged-in-user-url")
    pwgAjax.post(url, {}, onSuccess, onFailure)

  checkUser()

  deferred = null

