'use strict';

app.directive('userPanel', function() {
  return {
    restrict: 'EA',
    //replace: true,
    scope: {},
    template: '<a class="btn btn-nav pull-right" ng-click="showHelpModal()">' +
                '<i class="fa fa-question-circle fa-lg"></i>&nbsp;&nbsp;<span>Help</span>'+
              '</a>'+
    '<a class="btn btn-nav pull-right" ui-sref="home" ng-if="!currentUser && !dealer && !registerDealer">' +
                '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp;<span>Login &#47; Register</span>'+
              '</a>'+
    '<button class="btn btn-nav pull-right" ng-if="((currentUser && !currentUser.name && dealer && !menu && (!virtualEditor || !fileExplorer)) || dealerJobsList || virtualEditorState || dealerSettingState) && !registerDealer" data-placement="bottom-right" data-html="1" data-trigger="click" bs-dropdown="dealerUsernameDropdown">' +
    '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp; {{dealerUsername}} &nbsp;<i class="fa fa-caret-down"></i>' +
    '</button>' +
    '<button class="btn btn-nav pull-right" ng-if="(((currentUser && !currentUser.name && dealer && !menu) && !dealerJobsList && !virtualEditorState) || (virtualEditor && !dealerJobsList && !virtualEditorState)) && !registerDealer && !dealerSettingState" data-placement="bottom-right" data-html="1" data-trigger="click" bs-dropdown="virtualEditorDropdown">' +
    '<i class="fa fa-circle fa-lg"></i>&nbsp;&nbsp;<span>Virtual Editor</span> &nbsp;<i class="fa fa-caret-down"></i>' +
    '</button>' +
    '<button class="btn btn-nav pull-right" ng-if="currentUser && !dealer && !dealerJobsList && !virtualEditorState && !virtualEditor && !dealerSettingState" data-placement="bottom-right" data-html="1" data-trigger="click" bs-dropdown="dropdown">' +
                '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp; {{currentUser.username}} &nbsp;<i class="fa fa-caret-down"></i>'+
              '</button>',
    controller: function ($rootScope, $scope, $state, $window, $modal, toastr, Auth, User, Systems) {

      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (toState.name.match('menu')) {
          $scope.menu = true;
        } else {
          $scope.menu = false;
        }

        if (toState.name.match('file-explorer')) {
          $scope.fileExplorer = true;
        } else {
          $scope.fileExplorer = false;
        }

        if (toState.name.match('dealer-jobs-list')) {
          $scope.dealerJobsList = true;
        } else {
          $scope.dealerJobsList = false;
        }

        if (toState.name.match('virtual-editor')) {
          $scope.virtualEditorState = true;
        } else {
          $scope.virtualEditorState = false;
        }

        if (toState.name.match('register-dealer')) {
          $scope.registerDealer = true;
        } else {
          $scope.registerDealer = false;
        }

        if (toState.name.match('dealer-account-settings')) {
          $scope.dealerSettingState = true;
        } else {
          $scope.dealerSettingState = false;
        }

        if ($rootScope.virtualEditor) {
          $scope.virtualEditor = true;
        } else {
          $scope.virtualEditor = false;
        }
      });

      Systems.getSystemEnv().then(function(response) {
        $scope.eulaLink = response.eulaLink;
        $scope.downloadsTitle = response.downloadsTitle;
        $scope.remoteOwnersManualLink = response.remoteOwnersManualLink;
        $scope.remoteOwnersManualFile = response.remoteOwnersManualFile;
        $scope.bsOwnersManualLink = response.bsOwnersManualLink;
        $scope.bsOwnersManualFile = response.bsOwnersManualFile;
        $scope.installationGuideLink = response.installationGuideLink;
        $scope.installationGuideFile = response.installationGuideFile;
        $scope.programmingGuideLink = response.programmingGuideLink;
        $scope.programmingGuideFile = response.programmingGuideFile;
        $scope.quickStartGuideLink = response.quickStartGuideLink;
        $scope.quickStartGuideFile = response.quickStartGuideFile;
        $scope.advancedDevicesQuickGuideLink = response.advancedDevicesQuickGuideLink;
        $scope.advancedDevicesQuickGuideFile = response.advancedDevicesQuickGuideFile;
        $scope.zWaveIntegrationLink = response.zWaveIntegrationLink;
        $scope.zWaveIntegrationFile = response.zWaveIntegrationFile;
        $scope.cameraIntegrationLink = response.cameraIntegrationLink;
        $scope.cameraIntegrationFile = response.cameraIntegrationFile;
        $scope.dealerAccessLink = response.dealerAccessLink;
        $scope.dealerAccessFile = response.dealerAccessFile;
        $scope.mobileAppQuickGuideLink = response.mobileAppQuickGuideLink;
        $scope.mobileAppQuickGuideFile = response.mobileAppQuickGuideFile;
        $scope.usingFavoriteChannelsLink = response.usingFavoriteChannelsLink;
        $scope.usingFavoriteChannelsFile = response.usingFavoriteChannelsFile;
      }).catch(function(error) {
        toastr.error(error);
      });

      $scope.viewApplyForDealer = function () {
        window.open('/#/apply-for-dealer', 'Apply for a dealer account', 'scrollbars=no, height=800')
      };

      $scope.currentUser = null;
      $scope.dealer = null;

      $scope.logoutUser = function () {
        User.logout();
        $('.user-panel').css('visibility', 'hidden');
        $window.location.href = '/';
      };

      $scope.$on('user:set', function(event, currentUser) {
        console.log('caught user:set event');

        $scope.dealer = null;

        if (currentUser.username || currentUser.company) {
          $scope.currentUser = currentUser;
        }

        if (currentUser.company) {
          $scope.dealerUsername = currentUser.dealer_username;

          var fileExplorer = _.findWhere($scope.dropdown, {
            href: '/#/file-explorer'
          });

          if (!fileExplorer) {
            $scope.dropdown.push({
              "text": '<i class="fa fa-exclamation-triangle" />&nbsp;&nbsp;File Explorer',
              "href": "/#/file-explorer",
              "target": "_self"
            });

            $scope.dropdown.push({
              "text": '<i class="fa fa-list-alt" />&nbsp;&nbsp;Dealer Jobs List',
              "href": "/#/dealer-jobs-list",
              "target": "_self"
            });
          }

          if (!currentUser.username) {
            $scope.dealer = true;
          }
        }
      });

      $scope.$on('user:unset', function(event) {
        console.log('caught user:unset event');
        $scope.currentUser = null;
      });


      $scope.switch = {};

      var helpModal = $modal({
        scope: $scope,
        placement: 'top',
        template: 'views/modal-tpls/help.html',
        show: false
      });

      $scope.switchUpdate = false;
      $scope.$on('modal.hide',function(){
        if ($scope.switchUpdate) {
          location.reload();
        }
      });

      $scope.showHelpModal = function() {
        if($scope.currentUser) {
          $scope.switch.menu = !!$scope.currentUser.optMenuShow;
          $scope.switch.help = !!$scope.currentUser.optHelpShow;
        }

        helpModal.$promise.then(helpModal.show);
      };

      $scope.$watch('switch.help', function(newValue, oldValue) {
        var optHelpShow,
          user;

        if (newValue != oldValue && typeof oldValue != 'undefined') {
          $scope.switchUpdate = true;

          if (newValue) {
            optHelpShow = 1;
          } else {
            optHelpShow = 0;
          }

          user = JSON.parse($window.localStorage.getItem('hcm_editor'));
          user.optHelpShow = optHelpShow;
          Auth.setCurrentUser(user);

          var jsonData = JSON.stringify({help_show: user.optHelpShow, menu_show: user.optMenuShow});
          User.setOption(jsonData);
        }
      });

      $scope.$watch('switch.menu', function(newValue, oldValue) {
        var optMenuShow,
          user;

        if (newValue != oldValue && typeof oldValue != 'undefined') {
          $scope.switchUpdate = true;

          if (newValue) {
            optMenuShow = 1;
          } else {
            optMenuShow = 0;
          }

          user = JSON.parse($window.localStorage.getItem('hcm_editor'));
          user.optMenuShow = optMenuShow;
          Auth.setCurrentUser(user);

          var jsonData = JSON.stringify({help_show: user.optHelpShow, menu_show: user.optMenuShow});
          User.setOption(jsonData);
        }
      });


      $scope.dropdown = [
        {
          "text": '<i class="fa fa-list" />&nbsp;&nbsp;Overview',
          "href": "/#/menu/system-overview",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-users" />&nbsp;&nbsp;Account Settings',
          "href": "/#/account-settings",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-gears" />&nbsp;&nbsp;System Settings',
          "href": "/#/system-settings",
          "target": "_self"

        },
        {
          "text": '<i class="fa fa-sign-out" />&nbsp;&nbsp;Logout',
          "click": "logoutUser()"
        }
      ];

      $scope.virtualEditorDropdown = [
        {
          "text": '<i class="fa fa-list" />&nbsp;&nbsp;Overview',
          "href": "/#/menu/system-overview",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-sign-out" />&nbsp;&nbsp;Logout',
          "click": "logoutUser()"
        },
        {
          "text": '<i class="fa fa-exclamation-triangle" />&nbsp;&nbsp;File Explorer',
          "href": "/#/file-explorer",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-list-alt" />&nbsp;&nbsp;Dealer Jobs List',
          "href": "/#/dealer-jobs-list",
          "target": "_self"
        }
      ];

      $scope.dealerUsernameDropdown = [
        {
          "text": '<i class="fa fa-circle" />&nbsp;&nbsp;Virtual Editor',
          "href": "/#/virtual-editor",
          "target": "_self"
        },
        {
          "text": '<i class="fa fa-sign-out" />&nbsp;&nbsp;Logout',
          "click": "logoutUser()"
        }
      ];


    }
  };
});
