'use strict';
/**
 * @ngdoc controller
 * @name DbEditController
 * @description
 *  db edit 화면
 */
app.controller('DbEditController', function($scope, $state, $sanitize, $modal, $timeout, toastr, categories, Systems) {
  $scope.tabs = [
    { heading: $sanitize('<i class="fa fa-laptop tab-icon"></i><span class="tab-title">Programming Menu</span>'), route:'menu.programming.options', active:true },
    { heading: $sanitize('<i class="fa fa-wrench tab-icon"></i><span class="tab-title">Advanced Menu</span>'), route:'menu.advanced.options', active:false },
    { heading: $sanitize('<i class="fa fa-globe tab-icon"></i><span class="tab-title">Home Overview</span>'), route:'menu.system-overview', active:false },
    { heading: $sanitize('<i class="fa fa-download tab-icon"></i><span class="tab-title">Download</span>'), route:'menu.download', active:false }
  ];

  $scope.go = function(route){
    // programming 메뉴로는 이동할 필요 없음, 로딩시 programming 메뉴가 active tab 이라서 자동으로 이동하는 것을 막기 위해 예외 처리.
    if (route !== 'menu.programming.options') {
      $state.go(route);
    }
  };

  $scope.dbEdit = {};
  $scope.dbEdit.categories = categories;
  $scope.dbEdit.versions = [
    {
      name: 'Alpha',
      value: 3
    },
    {
      name: 'Beta + Alpha',
      value: 2
    },
    {
      name: 'Public + Beta + Alpha',
      value: 0
    }
  ];

  $scope.dbEdit.category = null;
  $scope.dbEdit.brand = null;
  $scope.dbEdit.model = null;

  $scope.dbEdit.newCategory = {
    id: null,
    name: null
  };
  $scope.dbEdit.newBrand = {
    id: null,
    name: null
  };
  $scope.dbEdit.newModel = {
    id: null,
    name: null
  };

  $scope.selectCategory = function(category) {
    $scope.dbEdit.brand = null;
    $scope.dbEdit.model = null;

    Systems.getTwowayBrands(category.id).then(function(response) {
      $scope.dbEdit.brands = response;
    }, function(error) {
      toastr.error(error);
    });
  };

  $scope.selectBrand = function(brand) {
    $scope.dbEdit.model = null;

    Systems.getTwowayModels(brand.id).then(function(response) {
      $scope.dbEdit.models = response;
    }, function(error) {
      toastr.error(error);
    });
  };

  $scope.selectModel = function(model) {
    //console.log(model);
  };

  $scope.addCategory = function() {
    var newCategory = angular.copy($scope.dbEdit.newCategory);
    if (!$scope.dbEdit.categories || !$scope.dbEdit.categories.length) {
      $scope.dbEdit.categories = [newCategory];
    } else {
      $scope.dbEdit.categories.push(newCategory);
    }
    $scope.dbEdit.category = newCategory;

    $scope.dbEdit.newCategory = {
      id: null,
      name: null
    };
  };

  $scope.addBrand = function() {
    var newBrand = angular.copy($scope.dbEdit.newBrand);
    if (!$scope.dbEdit.brands || !$scope.dbEdit.brands.length) {
      $scope.dbEdit.brands = [newBrand];
    } else {
      $scope.dbEdit.brands.push(newBrand);
    }
    $scope.dbEdit.brand = newBrand;

    $scope.dbEdit.newBrand = {
      id: null,
      name: null
    };
  };

  $scope.addModel = function() {
    var newModel = angular.copy($scope.dbEdit.newModel);
    if (!$scope.dbEdit.models || !$scope.dbEdit.models.length) {
      $scope.dbEdit.models = [newModel];
    } else {
      $scope.dbEdit.models.push(newModel);
    }
    $scope.dbEdit.model = newModel;

    $scope.dbEdit.newModel = {
      id: null,
      name: null
    };
  };

  $scope.getDbTwowayModel = function() {
    var data = {
        categoryId: $scope.dbEdit.category.id,
        category: $scope.dbEdit.category.name,
        brandId: $scope.dbEdit.brand.id,
        brand: $scope.dbEdit.brand.name,
        modelId: $scope.dbEdit.model.id,
        model: $scope.dbEdit.model.name
      },
      jsonData = JSON.stringify(data);

    Systems.getDbTwowayModel(jsonData).then(function(response) {
      $scope.dbEdit.version = _.find($scope.dbEdit.versions, function(obj) {
        return obj.value === response.version;
      });
      $scope.dbEdit.major = response.major;

      var obj = angular.copy(response);
      delete(obj.major);
      delete(obj.name);
      delete(obj.version);

      $scope.dbEdit.data = JSON.stringify(obj);

      toastr.success('Success: Get');
    }, function(error) {
      toastr.error(error);
    });
  };

  $scope.addDbTwowayModel = function() {
    try {
      var parsedData = JSON.parse($scope.dbEdit.data);
      if (!parsedData.variables) {
        parsedData.variables = "";
      }

      var data = {
          categoryId: $scope.dbEdit.category.id,
          category: $scope.dbEdit.category.name,
          brandId: $scope.dbEdit.brand.id,
          brand: $scope.dbEdit.brand.name,
          modelId: $scope.dbEdit.model.id,
          model: $scope.dbEdit.model.name,
          data: JSON.stringify(parsedData),
          version: $scope.dbEdit.version.value,
          major: $scope.dbEdit.major || 0
        },
        jsonData = JSON.stringify(data);

      Systems.addDbTwowayModel(jsonData).then(function(response) {
        toastr.success('Success: Add New');
      }, function(error) {
        toastr.error(error);
      });
    } catch(e) {
      toastr.error('Module data is invalid. Please check JSON format.');
    }
  };

  $scope.setDbTwowayModel = function() {
    try {
      var parsedData = JSON.parse($scope.dbEdit.data);
      if (!parsedData.variables) {
        parsedData.variables = "";
      }

      var data = {
          categoryId: $scope.dbEdit.category.id,
          category: $scope.dbEdit.category.name,
          brandId: $scope.dbEdit.brand.id,
          brand: $scope.dbEdit.brand.name,
          modelId: $scope.dbEdit.model.id,
          model: $scope.dbEdit.model.name,
          data: JSON.stringify(parsedData),
          version: $scope.dbEdit.version.value,
          major: $scope.dbEdit.major || 0
        },
        jsonData = JSON.stringify(data);

      Systems.setDbTwowayModel(jsonData).then(function(response) {
        toastr.success('Success: Set');
      }, function(error) {
        toastr.error(error);
      });
    } catch(e) {
      toastr.error('Module data is invalid. Please check JSON format.');
    }
  };

  $scope.showModal = function(mode) {
    var templateUrl = 'views/modal-tpls/db-edit/' + mode + '.html';

    var modal = $modal({
      scope: $scope,
      template: templateUrl,
      container: 'body',
      show: false
    });
    modal.$promise.then(modal.show);
  };

  $scope.clearAll = function() {
    $scope.dbEdit.brands = [];
    $scope.dbEdit.models = [];

    $scope.dbEdit.category = null;
    $scope.dbEdit.brand = null;
    $scope.dbEdit.model = null;
    $scope.dbEdit.version = null;
    $scope.dbEdit.major = 0;
    $scope.dbEdit.data = null;

    $scope.dbEdit.newCategory = {
      id: null,
      name: null
    };
    $scope.dbEdit.newBrands = {
      id: null,
      name: null
    };
    $scope.dbEdit.newModels = {
      id: null,
      name: null
    };

    toastr.success('Success: Clear All');
  };
});
