'use strict';


app.controller('AddToDealerController', function ($rootScope, $scope, $state, $modal, toastr, currentSystem, Dealer, Systems, User) {

  $scope.setDealer = function() {
    var systemId = currentSystem.id;

    var jsonData = JSON.stringify($scope.credentials);

    Systems.setDealer(systemId, jsonData)
      .then( function(data) {
        if(data.result) {
          $rootScope.dealerCompany = data.company;

          var modal = $modal({
            scope: $scope,
            title: '',
            placement: 'top',
            template: 'views/modal-tpls/dealer/dealer-system-added.html',
            backdrop: 'static',
            show: false
          });

          modal.$promise.then(modal.show);
        } else {
          toastr.error(data.error);
        }
      })
      .catch(toastr.error);

    // 일반 사용자에서 logout 하고 delaer 로 로그인 후 system 선택 후 home overview 화면으로 이동
    // system 선택 후 home overview 화면으로 이동하는 코드는 DealerJobsListController 의 $scope.selectSystem function 과 같음
    $scope.dealerLogin = function () {
      User.logout();

      Dealer.login(jsonData)
        .then(function (data) {
          if (data.result) {
            // dealer company 불러오기
            $rootScope.dealerCompany = Dealer.getDealerCompany();

            Dealer.getSystemToken(JSON.stringify({system_id: systemId})).then(function (data) {
              if (data.result) {
                // token 갱신
                var token = data.token;
                Dealer.setUser(systemId, token, false, false, true);   // dealer token 보존

                User.getUserInfo().then(function (data) {
                  // token 갱신
                  Dealer.setUser(systemId, token, data.username, data.email);

                  // system select
                  Systems.setCurrentRoom(null);

                  Systems.updateSystem(systemId).then(
                    function () {
                      $state.go('menu.system-overview');
                    },
                    function (error) {
                      toastr.error(error);
                    }
                  );
                }).catch(toastr.error);
              } else {
                toastr.error(data.error);
              }
            })
              .catch(toastr.error);
          } else {
            toastr.error(data.error);
          }
        })
        .catch(toastr.error);
    };
  };

  $scope.forgot = function() {
    var modal = $modal({
      scope: $scope,
      title: '',
      placement: 'top',
      template: 'views/modal-tpls/dealer/dealer-forgot-password.html',
      backdrop: 'static',
      show: false
    });

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

app.controller('DealerJobsListController', function ($rootScope, $scope, $state, $modal, toastr, jobsList, Systems, Dealer, User) {
  $rootScope.virtualEditor = null;

  $scope.jobsList = jobsList;
  $scope.selectedJob = null;

  $scope.viewDetails = function(job) {
    $scope.selectedJob = null;

    var jsonData = JSON.stringify({system_id: job.id});

    Dealer.getJob(jsonData).then(function(data) {
      if(data.result) {
        $scope.selectedJob = data.job;
        console.log($scope.selectedJob);

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

        modal.$promise.then(modal.show);
      } else {
        toastr.error(data.error);
      }
    })
    .catch(toastr.error);
  };

  // system 을 선택할 경우, 해당 system 의 user 권한으로 작업을 수행하기 위해 그 user 의 token 으로 업데이트함
  $scope.selectSystem = function() {
    if (!$scope.selectedJob) {
      return;
    }

    var jsonData = JSON.stringify({system_id: $scope.selectedJob.id});

    Dealer.getSystemToken(jsonData).then(function(data) {
      if(data.result) {
        // token 갱신
        var token = data.token;
        Dealer.setUser($scope.selectedJob.id, token, false, false, true);   // dealer token 보존

        User.getUserInfo().then(function(data) {
          // token 갱신
          Dealer.setUser($scope.selectedJob.id, token, data.username, data.email);

          // system select
          Systems.setCurrentRoom(null);

          Systems.updateSystem($scope.selectedJob.id).then(
            function () {
              $state.go('menu.system-overview');
            },
            function (error) {
              toastr.error(error);
            }
          );
        }).catch(toastr.error);
      } else {
        toastr.error(data.error);
      }
    })
      .catch(toastr.error);
  };

});

app.controller('FileExplorerController', function ($scope, $state, $modal, toastr, Systems) {

  

});

app.controller('ExportTemplateChooseRoomController', function ($scope, $state, $modal, toastr, Systems) {

  $scope.doNext = function() {
    $state.go('file-explorer.export-template');
  };

});

app.controller('ExportTemplateController', function ($scope, $state, $modal, toastr, Systems, Dealer) {
  
  $scope.showHelpModal = function() {
    var modal = $modal({
      scope: $scope,
      title: '',
      placement: 'top',
      template: 'views/modal-tpls/dealer/export-template-help.html',
      show: false
    });

    modal.$promise.then(modal.show);
  };
  
  $scope.finish = function() {
    var jsonData = JSON.stringify({
      roomId: $scope.exportTemplate.room.id,
      name: $scope.exportTemplate.filename
    });

    Dealer.createFromExisting(jsonData).then(function(data) {
      if (data.result) {
        var modal = $modal({
          scope: $scope,
          title: '',
          content: 'This room template has been exported to your Dealer Account File Explorer.',
          placement: 'top',
          template: 'views/modal-tpls/dealer/file-explorer.html',
          backdrop: 'static',
          show: false
        });

        modal.$promise.then(modal.show);
      }
    })
      .catch(toastr.error);
  };

});

app.controller('ExportDeviceChooseRoomController', function ($scope, $state, $modal, toastr, Systems) {

  $scope.doNext = function() {
    $state.go('file-explorer.export-device-choose-device');
  };

});

app.controller('ExportDeviceChooseDeviceController', function ($scope, $state, $modal, toastr, Systems) {

  $scope.doNext = function() {
    $state.go('file-explorer.export-device');
  };

});

app.controller('ExportDeviceController', function ($rootScope, $scope, $state, $modal, toastr, Systems, Dealer) {

  $scope.finish = function() {
    var jsonData = JSON.stringify({
      roomId: $scope.exportDevice.room.id,
      deviceId: $scope.exportDevice.device.id,
      name: $scope.exportDevice.filename
    });

    if ($rootScope.virtualEditor) {
      Dealer.customDevCreateFromTemplate(jsonData).then(function (data) {
        if (data.result) {
          var modal = $modal({
            scope: $scope,
            title: '',
            content: 'This entertainment device file has been exported to your Dealer Account File Explorer.',
            placement: 'top',
            template: 'views/modal-tpls/dealer/file-explorer.html',
            backdrop: 'static',
            show: false
          });

          modal.$promise.then(modal.show);
        }
      })
        .catch(toastr.error);
    } else {
      Dealer.customDevCreate(jsonData).then(function (data) {
        if (data.result) {
          var modal = $modal({
            scope: $scope,
            title: '',
            content: 'This entertainment device file has been exported to your Dealer Account File Explorer.',
            placement: 'top',
            template: 'views/modal-tpls/dealer/file-explorer.html',
            backdrop: 'static',
            show: false
          });

          modal.$promise.then(modal.show);
        }
      })
        .catch(toastr.error);
    }
  };

});

app.controller('ImportTemplateController', function ($rootScope, $scope, $state, $modal, toastr, templates, Systems, Dealer) {

  $scope.importTemplate.templates = templates;

  $scope.copyFromTemplate = function () {
    var jsonData = JSON.stringify({roomId: $scope.importTemplate.template.id});

    Dealer.copyFromTemplate(Systems.getCurrentRoom(), jsonData).then(function (data) {
      if (data.result) {
        console.log(data);

        var modal = $modal({
          scope: $scope,
          title: '',
          placement: 'top',
          template: 'views/modal-tpls/dealer/import-template-finish-virtual-editor.html',
          backdrop: 'static',
          show: false
        });

        modal.$promise.then(modal.show);
      }
    })
      .catch(toastr.error);
  };

  $scope.finish = function () {
    if ($rootScope.virtualEditor) {
      $state.go('menu.programming.options');
    }
  };

  $scope.select = function(template) {
    $scope.importTemplate.template = template;

    if ($rootScope.virtualEditor) {
      var modal = $modal({
        scope: $scope,
        title: '',
        placement: 'top',
        template: 'views/modal-tpls/dealer/import-template-warning-virtual-editor.html',
        backdrop: 'static',
        show: false
      });

      modal.$promise.then(modal.show);
    } else {
      $state.go('file-explorer.import-template-choose-room');
    }
  };

  $scope.delete = function(template) {
    $scope.importTemplate.template = template;

    var modal = $modal({
      scope: $scope,
      title: '',
      placement: 'top',
      template: 'views/modal-tpls/dealer/delete-item.html',
      backdrop: 'static',
      show: false
    });

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

  $scope.deleteItem = function() {
    var currentRoomDelete = false;
    // 현재 load 된 room 을 삭제한 경우
    if ($scope.importTemplate.template.id === Systems.getCurrentRoom()) {
      currentRoomDelete = true;
    }

    Dealer.deleteTemplate($scope.importTemplate.template.id).then(function(data) {
      if (data.result) {
        $scope.importTemplate.template = null;

        Dealer.getTemplates().then(
          function(response) {
            $scope.importTemplate.templates = response.templates;

            if (currentRoomDelete) {
              $state.go('dealer-jobs-list');
            }
          },
          function(error) {
            toastr.error(error);
          }
        );
      }
    })
      .catch(toastr.error);
  };

});

app.controller('ImportTemplateChooseRoomController', function ($rootScope, $scope, $state, $modal, toastr, Systems, Dealer) {

  $scope.importTemplateApplyToExisting = function() {
    var jsonData;

    if ($rootScope.virtualEditor) {
      jsonData = JSON.stringify({roomId: $scope.importTemplate.template.id});

      Dealer.copyFromTemplate(Systems.getCurrentRoom(), jsonData).then(function (data) {
        if (data.result) {
          console.log(data);

          var modal = $modal({
            scope: $scope,
            title: '',
            placement: 'top',
            template: 'views/modal-tpls/dealer/import-template-finish-virtual-editor.html',
            backdrop: 'static',
            show: false
          });

          modal.$promise.then(modal.show);
        }
      })
        .catch(toastr.error);
    } else {
      jsonData = JSON.stringify({roomId: $scope.importTemplate.room.id, name: $scope.importTemplate.template.name});

      Dealer.templateApplyToExisting($scope.importTemplate.template.id, jsonData).then(function (data) {
        if (data.result) {
          console.log(data);

          var modal = $modal({
            scope: $scope,
            title: '',
            placement: 'top',
            template: 'views/modal-tpls/dealer/import-template-finish.html',
            backdrop: 'static',
            show: false
          });

          modal.$promise.then(modal.show);
        }
      })
        .catch(toastr.error);
    }
  };
  
  $scope.finish = function() {
    if ($rootScope.virtualEditor) {
      $state.go('menu.programming.options');
    } else {
      Systems.updateSystem(Systems.getCurrentSystem().id).then(function () {
        Systems.setCurrentRoom($scope.importTemplate.room.id);
        $state.go('menu.programming.options');
      });
    }
  };
  
  $scope.doNext = function() {
    if ($scope.importTemplate.room.id === 'new') {
      $state.go('file-explorer.import-template-choose-bstation');
    } else {
      var modal = $modal({
        scope: $scope,
        title: '',
        placement: 'top',
        template: 'views/modal-tpls/dealer/import-template-warning.html',
        backdrop: 'static',
        show: false
      });

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

});

app.controller('ImportTemplateChooseBstationController', function ($scope, $state, $modal, toastr, searchResults, Systems, Dealer) {

  $scope.bsType = 'BASESTATIONS';
  $scope.baseStations = searchResults.searchedDevices;

  $scope.finish = function() {
    var jsonData = JSON.stringify({
      systemId: Systems.getCurrentSystem().id,
      name: $scope.importTemplate.room.name,
      type: $scope.importTemplate.baseStation.name,
      bstationName: $scope.importTemplate.baseStation.name,
      bstationMac: $scope.importTemplate.baseStation.mac
    });

    Dealer.templateApplyToNew($scope.importTemplate.template.id, jsonData).then(function (data) {
      if (data.result) {
        console.log(data);

        var modal = $modal({
          scope: $scope,
          title: '',
          placement: 'top',
          template: 'views/modal-tpls/dealer/import-template-new-room-finish.html',
          backdrop: 'static',
          show: false
        });

        modal.$promise.then(modal.show);
      }
    })
      .catch(toastr.error);
  };

  $scope.doNext = function () {
    var currentSystem = Systems.getCurrentSystem();
    Systems.updateSystem(currentSystem.id).then(function () {
      Systems.setCurrentRoom(currentSystem.rooms[currentSystem.rooms.length - 1].id);   // 방금 추가한 room 을 선택
      $state.go('menu.programming.options');
    });
  };

});

app.controller('ImportDeviceController', function ($scope, $state, $modal, toastr, devices, Systems, Dealer) {

  $scope.importDevice.devices = devices;

  $scope.select = function(device) {
    $scope.importDevice.device = device;
    
    $state.go('file-explorer.import-device-choose-room', {deviceId: $scope.importDevice.device.id});
  };

  $scope.delete = function(device) {
    $scope.importDevice.device = device;
    
    var modal = $modal({
      scope: $scope,
      title: '',
      placement: 'top',
      template: 'views/modal-tpls/dealer/delete-item.html',
      backdrop: 'static',
      show: false
    });

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

  $scope.deleteItem = function() {
    Dealer.deleteDevice($scope.importDevice.device.id).then(function(data) {
      if (data.result) {
        $scope.importDevice.device = null;

        Dealer.getDevices().then(
          function(response) {
            $scope.importDevice.devices = response.devices;
          },
          function(error) {
            toastr.error(error);
          }
        );
      }
    })
      .catch(toastr.error);
  };

});

app.controller('ImportDeviceChooseRoomController', function ($rootScope, $scope, $state, $modal, device, toastr, Systems, Dealer) {
  _.extend($scope.importDevice.device, device);
  $scope.importDevice.device.target_type = $scope.importDevice.device.type;

  $scope.selections = $scope.importDevice;

  $scope.lightLevels = [ {'value': 0, 'label': 'Off'}, {'value': 1, 'label': 'Low'}, {'value': 2, 'label': 'Medium'}, {'value': 3, 'label': 'High'}];
  $scope.irPortOptions = [{name: 'All', value: 255}, {name: '1', value: 1}, {name: '2', value: 2}, {
    name: '3',
    value: 3
  }, {name: '4', value: 4}];

  $scope.ir = {target:0, port:255};



  $scope.editDevice = function() {
    var targetPort;

    if ($scope.selections.device.target_type === 1) {
      if ($scope.ir.target === 2) {
        targetPort = 0;
      } else {
        targetPort = $scope.ir.port;
      }
    } else {
      targetPort = $scope.selections.device.target_port;
    }

    var obj = {
      name: $scope.selections.device.device_name,
      targetType: $scope.selections.device.target_type,
      targetAddr: $scope.selections.device.target_addr,
      targetPort: targetPort,
      favEnable: 0,
      favDelay: 400,
      favEnter: 0,
      repeatMin: $scope.selections.device.repeat_min,
      repeatMacro: $scope.selections.device.repeat_macro,
      rampStart: $scope.selections.device.ramp_start,
      rampSpeed: $scope.selections.device.ramp_speed,
      roomId: $scope.selections.room.id
    };
    if (typeof $scope.selections.device.attr != 'undefined' && typeof $scope.selections.device.attr.auto_cr != 'undefined') {
      obj.autoCr = $scope.selections.device.attr.auto_cr;
    }

    var jsonData = JSON.stringify(obj);

    if ($rootScope.virtualEditor) {
      Dealer.deviceApplyToTemplate($scope.selections.device.id, jsonData).then(function (data) {
        if (data.result) {
          console.log(data);
          Systems.updateSystem(Systems.getCurrentSystem().id).then(function () {
            Systems.setCurrentRoom($scope.selections.room.id);
            $state.go('menu.programming.options');
          });
        }
      })
        .catch(toastr.error);
    } else {
      Dealer.deviceApply($scope.selections.device.id, jsonData).then(function (data) {
        if (data.result) {
          console.log(data);
          Systems.updateSystem(Systems.getCurrentSystem().id).then(function () {
            Systems.setCurrentRoom($scope.selections.room.id);
            $state.go('menu.programming.options');
          });
        }
      })
        .catch(toastr.error);
    }
  };

  $scope.cancelEdit = function() {

  };

  $scope.$watch('selections.device', function(newVal, oldVal) {
    $scope.selections.device.target_type = +newVal.target_type;
  }, true);

  $scope.doNext = function() {
    var modal = $modal({
      scope: $scope,
      title: 'Edit this device',
      template: 'views/modal-tpls/dealer/edit-device.html',
      backdrop: 'static',
      show: false
    });

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

});

app.controller('VirtualEditorController', function ($rootScope, $scope, $state, $modal, $window, toastr, Systems) {

  $scope.exitVirtualEditor = function() {
    $rootScope.virtualEditor = null;
    var user = JSON.parse($window.localStorage.getItem('hcm_editor_dealer'));
    delete(user.virtualEditor);
    $window.localStorage.setItem('hcm_editor_dealer', JSON.stringify(user));

    $state.go('dealer-jobs-list');
  };

});

app.controller('VirtualEditorStartNewTemplateController', function ($rootScope, $scope, $state, $modal, $window, toastr, Systems, Dealer) {

  $scope.finish = function() {
    var jsonData = JSON.stringify({
      name: $scope.startNewTemplate.name
    });

    Dealer.createNewTemplate(jsonData).then(function(data) {
      if (data.result) {
        var roomId = data.roomId;

        Dealer.getRoom(roomId).then(function (data) {
          var room = data.data;

          // 기존 프로그램과의 호환을 위해 가상의 bstation 생성
          if (!room.bstations) {
            room.bstations = [$rootScope.virtualBstation];
          }

          $rootScope.virtualSystem.id = room.id;
          $rootScope.virtualSystem.rooms = [room];
          Systems.loadSystem($rootScope.virtualSystem);
          Systems.setCurrentRoom(room.id);

          $rootScope.virtualEditor = true;
          var user = JSON.parse($window.localStorage.getItem('hcm_editor_dealer'));
          user.virtualEditor = 1;
          user.room_id = roomId;
          $window.localStorage.setItem('hcm_editor_dealer', JSON.stringify(user));

          $state.go('menu.programming.options');
        })
          .catch(toastr.error);
      }
    })
      .catch(toastr.error);
  };

});

app.controller('VirtualEditorEditTemplateController', function ($rootScope, $scope, $state, $modal, $window, toastr, Systems, Dealer) {

  $scope.select = function(template) {
    $scope.editTemplate.template = template;

    Dealer.getRoom(template.id).then(function (data) {
      var room = data.data;

      // 기존 프로그램과의 호환을 위해 가상의 bstation 생성
      if (!room.bstations) {
        room.bstations = [$rootScope.virtualBstation];
      }

      $rootScope.virtualSystem.id = room.id;
      $rootScope.virtualSystem.rooms = [room];
      Systems.loadSystem($rootScope.virtualSystem);
      Systems.setCurrentRoom(room.id);

      $rootScope.virtualEditor = true;
      var user = JSON.parse($window.localStorage.getItem('hcm_editor_dealer'));
      user.virtualEditor = 1;
      user.room_id = template.id;
      $window.localStorage.setItem('hcm_editor_dealer', JSON.stringify(user));

      $state.go('menu.programming.options');
    })
      .catch(toastr.error);
  };

});

app.controller('RegisterDealerController', function ($rootScope, $scope, $state, $stateParams, $http, toastr, email, Dealer, User) {
  // As3AQCjg58mH
  // VDTLGbXjS5RIWG
  // npLieg8pVH8
  // IuY82RFBx

  $scope.credentials = {
    creation_id: $stateParams.creationId,
    email: email,
    username: email,
    password: null
  };
  $scope.confirmed_password = null;

  $scope.register = function () {
    var jsonData = JSON.stringify($scope.credentials);

    Dealer.addUserFinal(jsonData).then(function (data) {
      if (data.result) {
        User.logout();
        window.location = '/';
      }
    })
      .catch(toastr.error);
  };

  // add_user_prepare 테스트용
  /*
   $scope.addUserPrepare = function() {
   var url = '/api/dealer/add_user_prepare',
   data = {
   email: 'master@linkit.kr',
   account_type: 'Dealer Installer/Programmer',
   first_name: 'Youngguk',
   last_name: 'Kim',
   phone_number: '01032047694'
   },
   jsonData = JSON.stringify(data);

   $http.post(url, jsonData)
   .success(function(response) {
   console.log(response);
   });
   };
   $scope.addUserPrepare();
   */

});

app.controller('DealerAccountSettingsController', function ($scope, $state, $stateParams, $http, toastr, Dealer, Auth) {

  $scope.dealerInfo.selectedUser = null;
  $scope.dealerInfo.addUser = {};
  $scope.dealerInfo.userData = null;

  Auth.currentUser().then(function (user) {
    $scope.dealerInfo.currentUser = user;
  });

});

app.controller('DealerChangeEmailController', function ($scope, $state, $modal, toastr, Dealer, User) {

  $scope.dealerInfo.changeEmail = {};

  $scope.save = function () {
    $scope.dealerInfo.changeEmail.old_email = $scope.dealerInfo.currentUser.dealer_username;
    var jsonData = JSON.stringify($scope.dealerInfo.changeEmail);

    Dealer.newEmail(jsonData).then(function (data) {
      if (data.result) {
        var modal = $modal({
          scope: $scope,
          title: 'Email Address Changed',
          content: 'The email address for this account has been changed. You will need to log in again with your new account credentials.',
          template: 'views/modal-tpls/dealer/dealer-settings-complete.html',
          backdrop: 'static',
          show: false
        });

        modal.$promise.then(modal.show);
      }
    })
      .catch(toastr.error);
  };

  $scope.finish = function () {
    User.logout();
    window.location = '/';
  };

});

app.controller('DealerChangePasswordController', function ($scope, $state, $modal, Dealer, User) {

  $scope.dealerInfo.changePassword = {};

  $scope.save = function () {
    $scope.dealerInfo.changePassword.email = $scope.dealerInfo.currentUser.dealer_username;
    var jsonData = JSON.stringify($scope.dealerInfo.changePassword);

    Dealer.newPassword(jsonData).then(function (data) {
      if (data.result) {
        var modal = $modal({
          scope: $scope,
          title: 'Password Changed',
          content: 'The password for this account has been changed. You will need to log in again with your new account credentials.',
          template: 'views/modal-tpls/dealer/dealer-settings-complete.html',
          backdrop: 'static',
          show: false
        });

        modal.$promise.then(modal.show);
      }
    })
      .catch(toastr.error);
  };

  $scope.finish = function () {
    User.logout();
    window.location = '/';
  };

});

app.controller('DealerSelectUserController', function ($scope, $state, $stateParams, toastr, users, Dealer) {

  $scope.users = users;

  $scope.doNext = function () {
    $state.go('dealer-account-settings.user-info');
  };

});

app.controller('DealerUserInfoController', function ($scope, $state, $modal, toastr, Dealer) {

  var jsonData = JSON.stringify({email: $scope.dealerInfo.selectedUser.email});

  Dealer.getUserData(jsonData).then(function (data) {
    if (data.result) {
      $scope.dealerInfo.userData = data.data;
    }
  })
    .catch(toastr.error);

  $scope.delete = function () {
    var modal = $modal({
      scope: $scope,
      title: '',
      placement: 'top',
      template: 'views/modal-tpls/dealer/delete-user.html',
      backdrop: 'static',
      show: false
    });

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

  $scope.deleteUser = function () {
    Dealer.deleteUser(jsonData).then(function (data) {
      if (data.result) {
        $state.go('dealer-account-settings.main');
      }
    })
      .catch(toastr.error);
  };

});

app.controller('DealerAddUserController', function ($scope, $state, $modal, toastr, categories, Dealer) {

  $scope.categories = categories;
  $scope.dealerInfo.addUser.account_type = $scope.categories[0].value;

  $scope.doNext = function () {
    var jsonData = JSON.stringify($scope.dealerInfo.addUser);

    Dealer.addUserPrepare(jsonData).then(function (data) {
      if (data.result) {
        $state.go('dealer-account-settings.main');
      }
    })
      .catch(toastr.error);
  };

});
