var angular = require('angular');
require('../modules');
require('../services/AppConfig');

var module = angular.module('commons.directives.sinoConfig');

/**
* 省份选择指令
* config {
*   selectItem 选中的省份
*   canConfirm 省份时候改变
* }
*/
module.directive('sinoConfig', function($http, $q, configService, CoreAppConfig) {
  return {
    restrict: 'E',
    templateUrl: 'views/commons/directives/sinoConfig.tpl.html',
    replace: true,
    scope: {
      config: '='
    },
    link: function(scope) {
      scope.result = {};
      function init() {
        return configService.getConfig()
        .then(function(data) {
          return scope.items = data;
        })
        .then(getDefaultItem)
        .then(function(defaultItem) {
          scope.defaultItem = defaultItem;
          scope.result.selectItem = scope.defaultItem;
          scope.config.selectItem = scope.defaultItem;
        });
      }
      init();

      scope.$watch('result.selectItem', function(value) {
        if (value) {
          scope.config.selectItem = value;
          configService.getConfig().then(function(items) {
            scope.config.canConfirm = !items || value.id !== scope.defaultItem.id;
          });

        }
      });

      /**
      * 获取当前app中的默认配置
      * 1、若果已经配置好的config的
      * 2、没有配置config的情况
      */
      function getDefaultItem(items) {
        var item;
        var serverId = CoreAppConfig.applicationConfig.getServerId();
        for (var i = 0, len = items.length; i < len; i++) {
          item = items[i];
          if ((serverId && serverId === item.id) ||
            ((!serverId) && item['default'])) {
            return item;
          }
        }
      }
    }
  };
});
