"use strict";
appCore.controller("AclProfileCtrl", ["$state", "$scope", "$http", "$timeout", "vServices",
  function ($state, $scope, $http, $timeout, vServices) {
    $scope.$root.page.title = "ACL Profile";
    $scope.btn = {text: "Save"};
    $scope.cCode = ["primary", "success", "warning", "danger", "indigo", "navy", "purple", "maroon", "lime", "teal", "olive", "orange", "fuchsia"];

    // TODO To make this dynamic
    $scope.masters = [];
    $scope.heroes = [];
    $scope.heroesAdmin = [];
    $scope.acllist = [];
    $scope.acls = [];
    $scope.selHeroes = {model:[]};
    $scope.reqData = {profile_name:'',status:'true',acl_ids: []};
    $scope.acl = [];
    
    
    $scope.save = () => { 
      $scope.acls.forEach((o) => o.selected ? $scope.reqData.acl_ids.push(o.acl_id) : "");
      $scope.reqData.acl_ids = $scope.reqData.acl_ids.toString();
      $scope.reqData.status = $scope.reqData.status == 'true' ? true : false;
      if($scope.reqData.profile_name.length > 50){
        toastr.error('Profile name cannot be more than 50 characters.');
      }else{
        vServices.callApi("acl/addProfile" , "POST",$scope.reqData).then(function (res) {
            if (res) toastr.success(res, "Success!", {timeOut: 5000});
            $state.go('AclProfileList', {}, {reload: true});
        });
      }
    };

    $scope.selectAll = (moduleType, idx) => {
      $scope.masters[idx].selected = !$scope.masters[idx].selected;
      $scope.acls.forEach((value, key) => {
        if (value.acl_module === moduleType)
          value["selected"] = $scope.masters[idx].selected;
      });
    };

    const init = function () {
      vServices.callApi("employee/allDataForACL", "GET", {}).then(function (res) {
        if (res && res.length > 0) {
          $scope.heroes = res;
        }
      });
      vServices.callApi("acl/all", "GET", {}).then(function (res) {
        if (res && res.length > 0) {
          $scope.masters = [];
          let tempDupHandler = [];
          for (let i = 0; i < res.length; i++) {
            const o = res[i];
            if (tempDupHandler.indexOf(o.acl_module) === -1) {
              tempDupHandler.push(o.acl_module);
              $scope.masters.push({name: o.acl_module, selected: false, count: 0, color: $scope.cCode[i % $scope.cCode.length]});
            }
            else {
              $scope.masters[$scope.masters.length - 1].count++;
            }
          }
          $scope.acls = res;
        }
      });
    };
    init();
  }
]);



