/// <reference path="../../includes.ts"/>
/// <reference path="kubernetesHelpers.ts"/>
/// <reference path="kubernetesPlugin.ts"/>

module Kubernetes {

  export var ReplicationControllers = controller("ReplicationControllers",
    ["$scope", "KubernetesModel", "KubernetesReplicationControllers", "KubernetesPods", "KubernetesState", "$templateCache", "$location", "$routeParams", "$http", "$timeout", "KubernetesApiURL",
      ($scope,  KubernetesModel: Kubernetes.KubernetesModelService,  KubernetesReplicationControllers:ng.resource.IResourceClass<any>, KubernetesPods:ng.resource.IResourceClass<any>, KubernetesState,
       $templateCache, $location:ng.ILocationService, $routeParams, $http, $timeout, KubernetesApiURL) => {

    $scope.kubernetes = KubernetesState;
    $scope.model = KubernetesModel;
    $scope.filterReplicationControllers = $scope.model.filterReplicationcontrollers;

    $scope.tableConfig = {
      data: 'model.replicationControllers',
      showSelectionCheckbox: true,
      enableRowClickSelection: false,
      multiSelect: true,
      selectedItems: [],
      filterOptions: {
        filterText: $location.search()["q"] || ''
      },
     columnDefs: [
         { field: '$oracleName',
           displayName: '服务名称',
           cellTemplate: $templateCache.get("idTemplate.html")
         },
         //{ field: '$replicas',
         //  displayName: 'Scale',
         //  cellTemplate:$templateCache.get("desiredReplicas.html")
         //},
         { field: '$pods.age',
           displayName: '启动时间',
           cellTemplate:$templateCache.get("ageTemplate.html")
         },
         { field: '$labelsText',
           displayName: '数据标签',
           cellTemplate: $templateCache.get("labelTemplate.html")
         },
         { field: '$pods',
           displayName: '连接参数',
           cellTemplate: $templateCache.get("connectParamTemplate.html")
         },
         { field: '$pods[0].$eventCount',
           displayName: '服务启动日志',
           cellTemplate: $templateCache.get("eventSummaryTemplate.html")
         },
         { field: '$podCounters',
           displayName: '服务状态',
           cellTemplate: $templateCache.get("podCountsAndLinkTemplate.html"),
           customSortField: (field) => {
             if(field.$podCounters.ready ){
                return 3;
             }else if(field.$podCounters.valid || field.$podCounters.waiting){
                return 2;
             }else if(field.$podCounters.error){
                return 0;
             }else{
                return 1;
             }
           }
         },
         { field: '$extractStatus',
           displayName: '数据汇总状态',
           cellTemplate: $templateCache.get("dataSummaryTemplate.html")
         }
       ]
    }

    Kubernetes.initShared($scope, $location, $http, $timeout, $routeParams, KubernetesModel, KubernetesState, KubernetesApiURL);

    $scope.deletePrompt = (selected) => {
      if (angular.isString(selected)) {
        selected = [{
          id: selected
        }];
      }
      UI.multiItemConfirmActionDialog(<UI.MultiItemConfirmActionOptions>{
        collection: selected,
        index: 'metadata.name',
        onClose: (result:boolean) => {
          if (result) {
            function deleteSelected(selected:Array<KubePod>, next:KubePod) {
              if (next) {                
                Kubernetes.resizeController($http, KubernetesApiURL, next, 0, () => {                
                   KubernetesReplicationControllers.delete({
                     id: getName(next)
                   }, undefined, () => {                     
                     if(next.metadata.labels.style === "oracle"){                        
                        Kubernetes.connectOracle($http, $timeout, "/java/console/api/cancelOracleConection", "delete", getName(next), 0);
                     }                    
                     deleteSelected(selected, selected.shift());
                   }, (error) => {
                     log.debug("Error deleting: ", error);
                     deleteSelected(selected, selected.shift());
                 });
                });
              }
            }
            deleteSelected(selected, selected.shift());
          }
        },
        title: '是否需要删除oracle服务？',
        action: '以下的oracle服务将会被删除:',
        okText: '删除',
        okClass: 'btn-danger',
        custom: "该服务删除后将会清除oracle对应服务的端口等资源占用，但不删除数据文件，是否删除，请确认！",
        customClass: "alert alert-warning",
        cancelText: "取消"
      }).open();
    }

    $scope.createRCs= () => { 
       $http({
               url: '/java/console/api/cancelOracleConection',
               dataType: 'json',
               method:'POST',
               params:{param: "data"}
           }).success(function(data,header,config,status){
               console.log("success");
           }).error(function(data,header,config,status){
               //log.warn("Failed to connect " + connectParam + " " + data + " " + status);
           });  
    }

    $scope.stopPrompt = (selected) =>{
      if (angular.isString(selected)) {
        selected = [{
          id: selected
        }];
      }

      UI.multiItemConfirmActionDialog(<UI.MultiItemConfirmActionOptions>{
        collection: selected,
        index: 'metadata.name',
        onClose: (result:boolean) => {
        if (result) {
           function stopSelected(selected:Array<KubePod>, next:KubePod) {
             if (next) {
               Kubernetes.resizeController($http, KubernetesApiURL, next, 0, () => {
                 if(next.metadata.labels.style === "oracle"){                   
                    Kubernetes.connectOracle($http, $timeout, "/java/console/api/cancelOracleConection", "stop", getName(next), 0);
                 }
                 stopSelected(selected, selected.shift());
               });
             }
           }
           stopSelected(selected, selected.shift());
         }
      },
      title: '是否需要停止oracle服务？',
      action: '以下的oracle服务将会被停止:',
      okText: '停止',
      okClass: 'btn-danger',
      custom: "该服务停止后将无法继续提供连接访问服务，但可通过启动按钮重新启动该服务以进行访问。是否停止，请确认",
      customClass: "alert alert-warning",
      cancelText: "取消"
    }).open();
   };

   $scope.reStartPrompt = (selected) => {
      function startSelected(selected:Array<KubePod>, next:KubePod){
         if(next){
            if(next.$replicas === 0)
               Kubernetes.resizeController($http, KubernetesApiURL, next, 1, () => {
                   console.log("restart " + next.metadata.name);
                   Kubernetes.connectOracle($http, $timeout, "/java/console/api/connectOracle", "reStart", getName(next), 0);
                   startSelected(selected, selected.shift());
               });
         }
      }
      startSelected(selected, selected.shift());
   };

   $scope.extractData = {
       items: null,
       selectedItem: $scope.filterReplicationControllers[0] || "",
       dialog: new UI.Dialog(),
       onOk: () => {
               var extractData = $scope.extractData;
               extractData.dialog.close();
               var filterReplicationController = extractData.selectedItem;
               Kubernetes.extractDataToOracle($http, extractData.items, filterReplicationController);
               extractData.selectedItem = $scope.filterReplicationControllers[0] || "";
       },
       open: (selected) => {
           var extractData = $scope.extractData;
           extractData.dialog.open();
           extractData.selectedItem = $scope.filterReplicationControllers[0] || "";
           extractData.items = selected;
           $timeout(() => {
               $('#newDataName').focus();
           }, 50);
       },
       close: () => {
           $scope.extractData.dialog.close();
       }
   };

  }]);
}
