'use strict';


app.controller('SystemSelectController', function ($scope, $state, toastr, resolvedSystems, Systems) {

  	$scope.systems = resolvedSystems;

    $scope.doNext = function(){
      Systems.setCurrentRoom(null);
      return Systems.updateSystem($scope.choice).then(
        function (data) {
          var masterBstation;
          _.each(data.rooms, function(room) {
            if (!masterBstation) {
              masterBstation = _.where(room.bstations, {
                master: 1
              })[0];
            }
          });
          if (!masterBstation) {
            $state.go('recovery-bstation.select', {rooms: angular.toJson(data.rooms)});
            return;
          }
        
          $state.go('menu.job-overview');
        },
        function (error) {
          toastr.error(error);
        }
      );
    };

});


app.controller('SystemDeleteController', function ($scope, $state, toastr, resolvedSystems, Systems, User) {

    $scope.systems = resolvedSystems;
    $scope.sysToDel = {};

    $scope.deleteSystem = function(){

      Systems.deleteSystem($scope.sysToDel.id).then(function (data) {

          if (Systems.getAll().length === 0) {
            User.logout().then(function() {
              $state.transitionTo('register', null, { reload: true, inherit: true, notify: true  });
            }); 
          } else if (Systems.getCurrentSystem().id === $scope.sysToDel.id) {
            $state.go('system-select');
          } else {
            $state.go('menu.job-overview');
          }     
        },
        function (error) {
          toastr.error(error);
        }
      );
    };

});

app.controller('SystemSettingsController', function ($scope, $modal, timeZones, currentSystem) { 
  
  $scope.system = currentSystem;
  $scope.timeZones = timeZones;

});

app.controller('JobOverviewController', function ($scope, $http, $modal, $popover, $state, toastr, Systems, Rooms, Database, Devices) {
  $scope.system = Systems.getCurrentSystem();
  $scope.selections = { 'selectedRoom': {}, 'selectedBstation': {}, 'selectedRemote': {}, 'selectedDevice': {}};
  $scope.jobId = Systems.getCurrentJobId();

  var favoriteOptionModal = $modal({
    scope: $scope,
    title: 'Add Favorite Channels to this device',
    placement: 'top',
    template: 'views/assistant/modal-tpls/job-overview/fav-option.html',
    container: '#job-overview',
    show: false
  });

  $scope.popover = { 'device': ''};

  $scope.findPunchDevice = function(room) {
    $scope.popover.punchName = _.find(room.devices, { 'id': $scope.popover.device.punch_vol }).name;
  };

  $scope.containsMaster = function(room) {
    return _.contains(_.pluck(room.bstations, 'master'), 1);
  };

  $scope.changeValue = function(value) {
    return value/1000;
  };

  $scope.isEntDevice = Database.checkIfEntertainment;

  $scope.showFavModal = function (room, device) {
    angular.copy(room, $scope.selections.selectedRoom);
    angular.copy(device, $scope.selections.selectedDevice);

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


  $scope.toggleFavorite = function(room, device) {
    var currentSystem = Systems.getCurrentSystem(),
            roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
          deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': device.id }),
        currentDevice = currentSystem.rooms[roomIndex].devices[deviceIndex];

    if (!_.isEqual(currentDevice, device)) {
      var jsonData =  { "favOption": device.fav_option, "favDelay": device.fav_delay, "favEnter": device.fav_enter  };
      console.log(jsonData);
      $http({
        method: 'POST',
        url: '/urcassistant/api/device/favorite/' + room.id + '/' + device.id,
        data : jsonData
      }).
      success(function(data) {
        if(data.result) {
          currentDevice.fav_option = device.fav_option;
          currentDevice.fav_delay = device.fav_delay;
          currentDevice.fav_enter = device.fav_enter;
          Systems.loadSystem(currentSystem);
          $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
        }
        else {
          toastr.error(data.error);
        }
      })
      .error(function(error) {
        toastr.error('Please try again');
      });
    }

  };
  
});

/**
 * @ngdoc controller
 * @name JobListController
 * @description
 *  Job List 화면
 */
app.controller('JobListController', function($scope, $location, $timeout, $modal, $state, availableModels, toastr, ngTableParams, Systems) {
  $scope.requests = {};
  $scope.selectedJobId = '';
  $scope.selectedCompanyName = '';
  $scope.jobOptionAction = 'start-job';
  $scope.availableModels = availableModels;

  $scope.empty = {
    type: 'HCM-C1',
    roomName: ''
  };

  $scope.searchOptions = [
    {
      name: 'Company Name',
      value: 'company_name'
    },
    {
      name: 'Job ID',
      value: 'job_id'
    },
    {
      name: 'Client ID',
      value: 'username'
    }
  ];
  $scope.filterType = 'company_name';

  $scope.search = function() {
    $scope.tableParams.filter({
      name: $scope.filterType,
      min: $scope.filterValue
    });
  };

  function parseSelection(str) {
    //str will be, for example, +status or -status
    return {
      name: str.substr(1),
      reverse: str.charAt(0) === '-' ? true:false
    };
  }

  // 목록 테이블 생성
  //ngTableParams: parameters, settings
  $scope.tableParams = new ngTableParams(
    {
      page: 1,            // show first page
      count: 10          // count per page
    },
    {
      total: 0,           // length of data
      getData: function($defer, params) {
        console.log(params.filter());
        var page = params.page();
        var total = params.total();
        var previousData = params.data;

        var options = { count: params.count() };
        var orderBy = params.orderBy();
        var sortingColumn = !_.isEmpty(orderBy) && parseSelection(orderBy[0]);
        var filter = params.filter();

        if (sortingColumn) {
          angular.extend(options, { orderBy: sortingColumn });
        }
        if (!_.isEmpty(filter)) {
          angular.extend(options, { filter: {
            name: filter.name,
            min: filter.min
          } });
        }
        if (page > 1  ) {
          angular.extend(options, {from: (page-1) * params.count()});
        }

        Systems.jobList(options)
          .then(function(data) {
            //If previous total does not equal

            params.total(data.length);
            $timeout(function() {
              console.log(params.total());

              //if (params.total() !== count) params.page(1);

              //$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
              $defer.resolve(data);
            }, 500);
          })
          .catch(function(error) {
            toastr.error(error);
            $defer.resolve(previousData);
          });
      }
    });

  // 목록에서 waiting 클릭해서 팝업 띄우기 / 팝업에서 GO 클릭
  $scope.jobOption = function(jobId, action, companyName) {
    var modal = $modal({
        scope: $scope,
        title: 'Job Option',
        template: 'views/assistant/modal-tpls/job-option.html',
        container: '.container',
        show: false
      }),
      jsonData;

    $scope.selectedJobId = jobId;
    $scope.selectedCompanyName = companyName;

    // 목록에서 waiting 클릭
    if (!action) {
      modal.$promise.then(modal.show);
    }
    // 팝업에서 GO 클릭
    else {
      // jobId 로 부터 job 생성
      if (action == 'start-job') {
        jsonData = JSON.stringify({jobId: jobId, startWithEmpty: 0});

        Systems.import(jsonData)
          .then(function(data) {
            console.log('start job success', data);

            $scope.goOverview(jobId);
          })
          .catch(toastr.error);
      }
      // system 생성
      else if (action == 'start-job-empty') {
        $scope.empty.roomName = '';

        var modal2 = $modal({
            scope: $scope,
            title: 'Start empty options',
            template: 'views/assistant/modal-tpls/start-job-empty.html',
            container: '.container',
            show: false
          });

        modal2.$promise.then(modal2.show);
      }
      // view job request
      else if (action == 'view-job-request') {
        Systems.setCurrentJobId($scope.selectedJobId);
        $scope.viewJobData();
      }
    }
  }

  // start job empty 선택후 열린 팝업에서 OK 클릭
  $scope.jobEmptyImport = function() {
    var jobId = $scope.selectedJobId,
      params = {
        jobId: jobId,
        startWithEmpty: 1,
        roomName: $scope.empty.roomName,
        modelType: $scope.empty.type,
        bstationName: $scope.empty.type
      },
      jsonData = JSON.stringify(params);

    Systems.import(jsonData)
      .then(function(data) {
        console.log('start job empty success', data);

        $scope.goOverview(jobId);
      })
      .catch(toastr.error);
  };

  // 목록에서 opened 클릭
  $scope.goOverview = function(jobId) {
    Systems.setCurrentJobId(jobId);

    var jsonData = JSON.stringify({jobId: jobId});

    Systems.getSystems(jsonData)
      .then(function(data) {console.log('get systems', data);
        // systems 배열에 있는 첫 번째 system 의 id 를 구함
        var systemId = data.systems[0].id;

        // 현재 system 으로 update
        Systems.setCurrentRoom(null);
        return Systems.updateSystem(systemId, jsonData).then(
          function (data) {
            $state.go('menu.job-overview');
          },
          function (error) {
            toastr.error(error);
          }
        );
      })
      .catch(toastr.error);
  };

  // 목록에서 ready 클릭해서 팝업 띄우기 / 팝업에서 버튼 클릭
  $scope.jobReady = function(jobId, action) {
    var modal = $modal({
      scope: $scope,
      title: 'Job Option',
      template: 'views/assistant/modal-tpls/job-ready.html',
      container: '.container',
      show: false
    });

    $scope.selectedJobId = jobId;

    // 목록에서 ready 클릭
    if (!action) {
      modal.$promise.then(modal.show);
    }
    // 팝업에서 버튼 클릭
    else {
      // view job request data
      if (action == 'view') {
        $scope.viewJobData(jobId);
      }
      // reopen
      else if (action == 'reopen') {
        var jsonData = JSON.stringify({jobId: jobId, status: 1});

        Systems.setStatus(jsonData)
          .then(function(data) {
            $scope.goOverview(jobId);
          })
          .catch(toastr.error);
      }
    }
  }

  // 검색, 정렬 초기화
  $scope.clearSorting = function() {
    $scope.filterType = 'title';
    $scope.filterValue = '';
    $scope.searchForm.$setPristine();

    $scope.tableParams.filter({});
    $scope.tableParams.sorting({});
  };
});

/**
 * @ngdoc controller
 * @name CompanyListController
 * @description
 *  Company List 화면
 */
app.controller('CompanyListController', function($scope, $location, $timeout, $modal, $state, availableModels, toastr, ngTableParams, User, Systems) {
  $scope.requests = {};
  $scope.availableModels = availableModels;

  $scope.empty = {
    companyId: null,
    userId: null,
    systemName: null,
    timezone_id: -1,
    timezone_dst: 1,
    time_type: 0,
    roomName: null,
    modelType: 'HCM-C1',
    bstationName: null
  };
  $scope.empty.bstationName = $scope.empty.modelType;

  $scope.searchOptions = [
    {
      name: 'Company Name',
      value: 'company_name'
    },
    {
      name: 'Client ID',
      value: 'username'
    }
  ];
  $scope.filterType = 'company_name';

  $scope.search = function() {
    $scope.tableParams.filter({
      name: $scope.filterType,
      min: $scope.filterValue
    });
  };

  function parseSelection(str) {
    //str will be, for example, +status or -status
    return {
      name: str.substr(1),
      reverse: str.charAt(0) === '-' ? true:false
    };
  }

  // 목록 테이블 생성
  //ngTableParams: parameters, settings
  $scope.tableParams = new ngTableParams(
    {
      page: 1,            // show first page
      count: 10          // count per page
    },
    {
      total: 0,           // length of data
      getData: function($defer, params) {
        console.log(params.filter());
        var page = params.page();
        var total = params.total();
        var previousData = params.data;

        var options = { count: params.count() };
        var orderBy = params.orderBy();
        var sortingColumn = !_.isEmpty(orderBy) && parseSelection(orderBy[0]);
        var filter = params.filter();

        if (sortingColumn) {
          angular.extend(options, { orderBy: sortingColumn });
        }
        if (!_.isEmpty(filter)) {
          angular.extend(options, { filter: {
            name: filter.name,
            min: filter.min
          } });
        }
        if (page > 1  ) {
          angular.extend(options, {from: (page-1) * params.count()});
        }

        User.companyList(options)
          .then(function(data) {
            //If previous total does not equal

            params.total(data.length);
            $timeout(function() {
              console.log(params.total());

              //if (params.total() !== count) params.page(1);

              //$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
              $defer.resolve(data);
            }, 500);
          })
          .catch(function(error) {
            toastr.error(error);
            $defer.resolve(previousData);
          });
      }
    });

  // 목록 클릭
  $scope.startOptionsModal = function(companyId, id) {
    $scope.empty.companyId = companyId;
    $scope.empty.userId = id;

    var modal = $modal({
        scope: $scope,
        title: 'Start options',
        template: 'views/assistant/modal-tpls/start-options.html',
        container: '.editor-container',
        show: false
      });

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

  // system 생성
  $scope.create = function() {
    var jsonData = JSON.stringify($scope.empty);

    Systems.createOne(jsonData)
      .then(function(data) {
        var jobId = data;

        $scope.goOverview(jobId);
      })
      .catch(toastr.error);
  };

  // Job Overview 화면으로 이동
  $scope.goOverview = function(jobId) {
    Systems.setCurrentJobId(jobId);

    var jsonData = JSON.stringify({jobId: jobId});

    Systems.getSystems(jsonData)
      .then(function(data) {console.log('get systems', data);
        // systems 배열에 있는 첫 번째 system 의 id 를 구함
        var systemId = data.systems[0].id;

        // 현재 system 으로 update
        Systems.setCurrentRoom(null);
        return Systems.updateSystem(systemId, jsonData).then(
          function (data) {
            $state.go('menu.job-overview');
          },
          function (error) {
            toastr.error(error);
          }
        );
      })
      .catch(toastr.error);
  };
});