/**
 *
 */
'use strict';
define(function () {
  var RolesCtrl = function (
    $scope,
    RolesFactory,
    FeatureTypeFactory,
    $timeout,
    gaDomUtils,
    $filter
    ) {
    /**
     * Create or update a role
     */
    $scope.editRole = function () {
      gaDomUtils.showGlobalLoader();
      //$scope.edit_resource.rightFeatures =  [];
      /*if(angular.isArray( $scope.dLBFeatureTypeData.leftData)) {
             $scope.dLBFeatureTypeData.leftData.forEach(function (x) {
             $scope.edit_resource.rightFeatures.push(x.uid);
             });
             }*/

      // authorizations
      var authorizations = [];
      for (var i in $scope.fullSelectedFeatures) {
        var ft = $scope.fullSelectedFeatures[i];

        var ftAuth = {
          item: ft.uid,
          read: ft.readRights > 0,
          write: ft.writeRights > 0,
          create: ft.createRight > 0,
          remove: ft.removeRight > 0,
          subItems: [],
        };
        for (var j in ft.attributes) {
          var attr = ft.attributes[j];
          //     console.log(attr);
          ftAuth.subItems.push({
            item: attr.name,
            read: attr.readRight ? true : false,
            write: attr.writeRight ? true : false,
            subItems: [],
          });
        }

        authorizations.push(ftAuth);
      }

      $scope.edit_resource.authorizations = authorizations;

      if ($scope.isNewResource) {
        RolesFactory.add($scope.edit_resource)
          .then(function () {
            $scope.isNewResource = false;
          })
          .finally(gaDomUtils.hideGlobalLoaderAfterTimeout);
      } else {
        RolesFactory.update($scope.edit_resource)
          .finally(gaDomUtils.hideGlobalLoaderAfterTimeout);
      }
    };

    /**
     * Role removal
     */
    $scope.removeRole = function () {
      RolesFactory.remove($scope.edit_resource.uid).then(function () {
        //$scope.tableParams.total($scope.currentResources.length).reload();
      });
    };

    /**
     * Roles loading
     */
    $scope.currentResources = RolesFactory.resources.roles;

    RolesFactory.get().then(function () {
      $scope.currentResources = RolesFactory.resources.roles;
      FeatureTypeFactory.get().then(function () {
        $scope.featuresList = FeatureTypeFactory.resources.featuretypes;
      });
    });

    $scope.geocatalogueNotFromApplication = true;

    /*
         Role -> FeatureTypes/Attributes Selection and rights
         */
    $scope.$on('data_modal', function () {
      $scope.rightFeaturesComplete = [];
      $scope.allWriteRights = false;
      $scope.allReadRights = false;

      if ($scope.edit_resource.rightFeatures.length > 0) {
        // transforms rightFeatures uid list into an array of FeatureTypes
        $scope.allFeaturesChecked.value =
            $scope.edit_resource.rightFeatures.length ==
            $scope.featuresList.length;
      }

      /**
       * When the list of selected features is modified : update fullSelectedFeatures
       */

      $scope.$watch(
          'edit_resource.rightFeatures',
          function (data) {
            $scope.fullSelectedFeatures = [];

            data.forEach(function (uid) {
              var ft = angular.copy(FeatureTypeFactory.getFeatureByUid(uid));
              // If the feature does't exist or has been deleted
              if (ft !== null && ft.uid != "") {
                // authorizations
                // //PATCH FRT C-ASD
                if ($scope.edit_resource.authorizations == null) {
                  $scope.edit_resource.authorizations = [];
                }
                var authIndex = $scope.edit_resource.authorizations
                .map(function (x) {
                  return x.item;
                })
                .indexOf(ft.uid);
                if (authIndex != -1) {
                  var auth = $scope.edit_resource.authorizations[authIndex];

                  ft.readRights = 0;
                  ft.writeRights = 0;

                  // make it checked when attributes length == 0
                  if (ft.attributes.length == 0) {
                    ft.readRight = true;
                    ft.writeRight = true;
                  }
                  auth.subItems.forEach(function (authItem) {
                    var ftAttributeIndex = ft.attributes
                    .map(function (x) {
                      return x.name;
                    })
                    .indexOf(authItem.item);
                    if (ftAttributeIndex != -1) {
                      var ftAttribute = ft.attributes[ftAttributeIndex];
                      if (authItem.read) {
                        ft.readRight = true;
                        ft.readRights++;
                        ftAttribute.readRight = true;
                      }
                      if (authItem.write) {
                        ft.writeRight = true;
                        ft.writeRights++;
                        ftAttribute.writeRight = true;
                      }
                    }
                  });

                  if (auth.create) {
                    ft.createRight = true;
                  }
                  if (auth.remove) {
                    ft.removeRight = true;
                  }
                }

                //console.log(ft);

                $scope.fullSelectedFeatures.push(ft);
              }
            });
            //$scope.checkListCfg.resources.data = $scope.fullSelectedFeatures;
          },
          true
      );
    });

    $scope.$watch(
        'fullSelectedFeatures',
        function (fts) {
          if (fts && fts.length > 0) {
            fts.forEach(function (ft) {
              ft.readRights = 0;
              ft.writeRights = 0;
              ft.attributes.forEach(function (attr) {
                if (attr.readRight) {
                  ft.readRights += 1;
                }
                if (attr.writeRight) {
                  ft.writeRights += 1;
                }
              });
            });
          }
        },
        1
    );

    /**
     * Toggle all write or read right for a feature
     * @param right
     * @param index
     */
    $scope.toggleRights = function (right, index) {
      var ft = $scope.fullSelectedFeatures[index],
          attributes = ft.attributes;
      var currentReadRight = ft.readRight;
      var currentWriteRight = ft.writeRight;

      // In case we remove read rigts: remove write rights
      if (right === 'read' && currentReadRight) {
        ft.writeRight = false;
      }
      // In case we add write rights: add read rights
      if (right === 'write' && !currentWriteRight) {
        ft.readRight = true;
      }

      // Put the allRights to false when removing one
      if (right === 'read' && currentReadRight) {
        $scope.allReadRights = false;
      }
      if (right === 'write' && currentWriteRight) {
        $scope.allWriteRights = false;
      }

      if (attributes.length > 0) {
        attributes.forEach(function (attr) {
          if (right === 'read') {
            if (currentReadRight) {
              attr.writeRight = false;
            }
            attr.readRight = !currentReadRight;
          }
          if (right === 'write') {
            if (!currentWriteRight) {
              attr.readRight = true;
            }
            attr.writeRight = !currentWriteRight;
          }
        });
      }
    };

    /**
     * All Read Rights
     */
    $scope.allReadRights = false;
    $scope.toggleAllReadRights = function () {
      $scope.allReadRights = !$scope.allReadRights;
      // if we remove all read rights, also remove all write rights
      if (!$scope.allReadRights) {
        $scope.allWriteRights = false;
        $scope.fullSelectedFeatures.forEach(function (f) {
          f.writeRight = false;
          f.attributes.forEach(function (ff) {
            ff.writeRight = false;
          });
        });
      }
      $scope.fullSelectedFeatures.forEach(function (f) {
        f.readRight = $scope.allReadRights;
        f.attributes.forEach(function (ff) {
          ff.readRight = $scope.allReadRights;
        });
      });
    };

    /**
     * All Write Rights
     */
    $scope.allWriteRights = false;
    $scope.toggleAllWriteRights = function () {
      $scope.allWriteRights = !$scope.allWriteRights;
      // if we give all write rights, also give all read rights
      if ($scope.allWriteRights) {
        $scope.allReadRights = true;
        $scope.fullSelectedFeatures.forEach(function (f) {
          f.readRight = true;
          f.attributes.forEach(function (ff) {
            ff.readRight = true;
          });
        });
      }
      $scope.fullSelectedFeatures.forEach(function (f) {
        f.writeRight = $scope.allWriteRights;
        f.attributes.forEach(function (ff) {
          ff.writeRight = $scope.allWriteRights;
        });
      });
    };

    /**
     * Check if all rights are checked or not, and change the ft.readRight/ft.writeRight according to it
     */
    $scope.checkFeatureRightsAmout = function (feature, attr, right) {
      $timeout(function () {
        // If we remove a read right, also remove the write right for the attribute, feature and all
        if (right === "read" && !attr.readRight) {
          attr.writeRight = false;
          $scope.allWriteRights = false;
          $scope.allReadRights = false;
        }
        // If we add a write right, also add a read right
        if (right === "write" && attr.writeRight) {
          attr.readRight = true;
        }

        feature.readRight = feature.readRights > 0;
        feature.writeRight = feature.writeRights > 0;
      });
    };

    /**
     * Check if all rights are checked or not, and change the ft.readRight/ft.writeRight according to it
     */
    $scope.checkFeatureRightsAmout2 = function (feature) {
      $timeout(function () {
        feature.readRight = feature.readRights > 0;
        feature.writeRight = feature.writeRight > 0;
      });
    };

    /**
     * toggle a single Right Feature
     * @param uid
     */
    $scope.toggleRightFeature = function (uid) {
      var index = $scope.edit_resource.rightFeatures.indexOf(uid);
      if (index != -1) {
        $scope.edit_resource.rightFeatures.splice(index, 1);
        $scope.allFeaturesChecked.value = false;
      } else {
        $scope.edit_resource.rightFeatures.push(uid);
      }
    };

    /**
     * toggle all the Right Features
     * @param uid
     */
    $scope.allFeaturesChecked = {};
    $scope.toggleAllRightFeatures = function () {
      var rf = [];
      if (!$scope.allFeaturesChecked.value) {
        $scope.featuresList.forEach(function (ft) {
          rf.push(ft.uid);
        });
      }
      $scope.edit_resource.rightFeatures = rf;
    };

    /**
     EditList Directive configuration
     */
    $scope.editListCfg = {
      dataModule: 'rights',
      resource_type: 'roles',
      cols: ['name', 'uid'],
      removeFunction: $scope.removeRole,
      defautValues: [{k: 'rightFeatures', v: []}],
    };

    $scope.validForm = {};
    $scope.validateName = function () {
      var actualName = $scope.edit_resource.name;
      $scope.$watch(
          'edit_resource.name',
          function (name) {
            $scope.nameExists =
                $scope.currentResources
                .map(function (r) {
                  return r.name;
                })
                .indexOf(name) != -1;
            if (!$scope.isNewResource && $scope.edit_resource.name
                == actualName) {
              $scope.nameExists = false;
            }
            $scope.validForm.name = !$scope.nameExists;
          },
          1
      );
    };
    $scope.widget = $filter('translate')('rights.roles.popupTitle');
  };

  RolesCtrl.$inject = [
    '$scope',
    'RolesFactory',
    'FeatureTypeFactory',
    '$timeout',
    'gaDomUtils',
    '$filter'
  ];
  return RolesCtrl;
});
