'use strict';
define(function() {
  var kisCalendarEvent = function(
    CalendarFactory,
    gaDomUtils,
    $filter,
    $rootScope,
    $location,
    $anchorScroll,
    UsersFactory,
    authFactory,
    ngDialog,
    FeatureTypeFactory,
    FunctionFactory,
    $timeout,
    gaJsUtils,
    AncAppFactory,
    kisCalendarFactory
  ) {
    return {
      templateUrl: 'js/XG/containers/views/kis_calendarevent.html',
      restrict: 'EA',
      scope: {
        map: '=?',
        currentEvent: '=',
        controleevent: '=?controleevent',
        currentagent: '=?currentagent',
        eventTypes: '=?',
        idEventType: '=?',
        dateMin: '=?',
        dateMax: '=?',
        color: '=?',
        notEditable: '=?',
        configValid: '=?',
        hideCloseButton: '@?', // hide close button
        hideUpdateButton: '@?', // hide update button
        cannotModify: '@?',
        onFinish: '&?', // optional onfinish, fired after event save/update
        defaultExtraData: '=?', // allow to feed relations, users, objects, documents, etc.. to a new object,
        setEventSize: '&',
        fromCalendar: '=?', // permet d'indiquer que l'event est inclu dans le calendar et pas en standalone ailleurs (taskmanager par ex)
        eventDisplay: '=?', // eventDisplay
        addCtrl: '=?',
        calendareventmin: '=?',
        rdvPossible: '=?',
        disableColorPicker: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.map = false;
        console.log(scope.addCtrl, scope.eventDisplay);
        var getMap = function() {
          if ($rootScope.xgos.sector == 'map') {
            scope.map = $rootScope.xgos.getMapAppMap();
            if (positionVectorLayer) scope.map.removeLayer(positionVectorLayer);
          }
        };
        getMap();

        if (scope.rdvPossible && scope.currentEvent && scope.currentEvent.properties && scope.currentEvent.properties.type_evenement) {
          scope.currentEvent.properties.type_evenement = 
            (scope.eventTypes.find(eventType => eventType.properties.type_id === scope.currentEvent.properties.type_evenement) || {}).type_id;
        }

        /**
         * get calendar geocodage config
         */
        //checkNestedProperty
        if (
          gaJsUtils.checkNestedProperty(
            'parameters.calendar.geocodage',
            $rootScope.xgos.portal
          )
        ) {
          scope.geocodage =
            $rootScope.xgos.portal.parameters.calendar.geocodage;
        }
        /**
         * get current user
         */
        scope.multiplePanels = {};
        scope.canModifyEvent = false;
        if (angular.isUndefined(scope.currentEvent)) {
          scope.currentEvent = {};
        }
        scope.multiplePanels.activePanels = [];

        scope.alerts = [];
        scope.currentUser = $rootScope.xgos.user;

        var refreshEventRelations = function() {
          CalendarFactory.geteventrelations(scope.currentEvent.id).then(
            function(res) {
              scope.currentEventRelations = res.data;
            }
          );
        };
        scope.$watch(
          'currentEvent.id',
          function(id) {
            scope.currentEventRelations = { features: [] };
            scope.uploadFileData = {
              id: scope.currentEvent.id,
              featuretype: 'kis_calendar_event',
            };
            if (id) refreshEventRelations();
            checkUserPermissions();
          },
          1
        );
        if (scope.currentEvent.id) {
          scope.uploadFileData = {
            id: scope.currentEvent.id,
            featuretype: 'kis_calendar_event',
          };

          checkUserPermissions();

          /**
           * get alerts from base by id_event
           */
          CalendarFactory.getalertsbyeventid(scope.currentEvent.id).then(
            function(res) {
              scope.alerts = [];
              for (var i = 0; i < res.data.features.length; i++) {
                var type = 'm';
                var value = res.data.features[i].properties.delai;
                scope.alerts.push({
                  value: returnAlertTypeOrValue(value, type, 'value'),
                  type: returnAlertTypeOrValue(value, type, 'type'),
                });
              }
            }
          );

          CalendarFactory.gettaskbyeventid(scope.currentEvent.id).then(function(
            res
          ) {
            if (res.data.features) {
              scope.currentTask = res.data.features[0];
            }
          });

          scope.currentFeatureUid = FeatureTypeFactory.getFeatureUidByName(
            'kis_calendar_event'
          );
        } else {
          $timeout(() => {
            scope.canModifyEvent = true;
          });
          //nouvel evenement
          if (!scope.currentEvent.properties)
            scope.currentEvent.properties = {};
          if (!scope.currentEvent.properties.start) {
            scope.currentEvent.properties.start = $filter('date')(
              moment(new Date())
                .hours(8)
                .minutes(0)
                .toDate(),
              'yyyy-MM-ddTHH:mm:ss.sssZ'
            );
          }
          /*scope.currentEvent.properties.start =
                        $filter('date')(moment(new Date()).hours(8).minutes(0).toDate(), "yyyy-MM-ddTHH:mm:ss.sssZ");*/
          
          scope.uploadFileData = {
            featuretype: 'kis_calendar_event',
          };

          if (angular.isDefined(scope.defaultExtraData)) {
            for (var i in scope.defaultExtraData) {
              scope[i] = scope.defaultExtraData[i];
            }
          }
        }

        if (angular.isUndefined(scope.currentEvent.properties)) {
          scope.currentEvent = { properties: {} };
        }

        if (angular.isDefined(scope.idEventType)) {
          scope.currentEvent.properties.type_evenement = scope.idEventType;
        }

        if (!angular.isDefined(scope.currentEvent.properties.color)) {
          if (!angular.isDefined(scope.color)) {
            scope.color = 'e74c3c';
          }
          scope.currentEvent.properties.color = scope.color;
        }

        if (!scope.currentEvent.properties.color) {
          scope.currentEvent.properties.color = 'e74c3c';
        }

        if (angular.isDefined(scope.configValid)) {
          if (
            scope.configValid.color === true &&
            angular.isDefined(scope.color)
          ) {
            scope.hasColor = true;
          }

          if (
            scope.configValid.type_evenement === true &&
            angular.isDefined(scope.idEventType)
          ) {
            scope.hasType = true;
          }
          //remove configValid.date_min
          if (
            scope.configValid.date_min === true &&
            angular.isDefined(scope.dateMin)
          ) {
            scope.currentEvent.properties.start = scope.dateMin;
            scope.hasDateMin = true;
          }

          if (
            scope.configValid.date_max === true &&
            angular.isDefined(scope.dateMax)
          ) {
            scope.currentEvent.properties.end = scope.dateMax;
            scope.hasDateMax = true;
          }
        }

        /**
         * get Event Types
         */
        var getEventTypes = function() {
          gaDomUtils.showGlobalLoader();
          if (scope.rdvPossible) { return; } // Make sure to not update the eventTypes if coming from agenda
          CalendarFactory.geteventtypes().then(
            function(res) {
              scope.eventTypes = CalendarFactory.resources.event_types;
              scope.showNoTypeAlert = true;
              gaDomUtils.hideGlobalLoader();
            },
            function() {
              gaDomUtils.hideGlobalLoader();
            }
          );
        };
        scope.showNoTypeAlert = false;
        if (!scope.eventTypes || !scope.eventTypes.length) {
          getEventTypes();
        }

        // whenever the list event types list is modified
        $rootScope.$on('editCalendarEventTypes', function() {
          if (angular.isUndefined(scope.eventTypes)) {
            getEventTypes();
          }
        });

        scope.isDefined = function(value) {
          var res = false;
          if (angular.isDefined(value)) {
            res = true;
          }
          return res;
        };

        /**
         * close
         */
        scope.closeEvent = function() {
          scope.currentEvent = false;
          $rootScope.$broadcast('closeNgDialogAgendaCtrl');

          $timeout(function() {
            scope.calendareventmin = true;
            $rootScope.$broadcast('kis_calendar_event_refresh');
          }, 200);
        };

        /**
         * set event object relation
         * @param features
         */
        var setEventRelations = function(features) {
          if (
            gaJsUtils.checkNestedProperty(
              'features.length',
              scope.currentEventRelations
            )
          ) {
            features.linked_objects = [
              {
                type: 'FeatureCollection',
                features: [],
              },
            ];
            for (
              var i = 0;
              i < scope.currentEventRelations.features.length;
              i++
            ) {
              features.linked_objects[0].features.push({
                type: 'Feature',
                properties: {
                  feature_id:
                    scope.currentEventRelations.features[i].properties
                      .feature_id,
                  feature_uid:
                    scope.currentEventRelations.features[i].properties
                      .feature_uid,
                },
              });
            }
          }
        };

        /**
         * prepare Email
         * @param recipients
         * @param title
         * @param content
         */
        var prepareEmail = function(recipients, title, content) {
          if (recipients && recipients.length) {
            recipients.forEach(function(recipient) {
              var mailDesc = [];
              mailDesc.push({
                name: 'mailTo',
                type: 'cst',
                value: [recipient],
              });
              mailDesc.push({
                name: 'mailSubject',
                type: 'cst',
                value: title,
              });
              mailDesc.push({
                name: 'mailContent',
                type: 'cst',
                value: content,
              });
              gaDomUtils.showGlobalLoader();
              FunctionFactory.execute(
                { parameters: mailDesc },
                'sendMail',
                'ja'
              ).then(
                function(res) {
                  gaDomUtils.hideGlobalLoader();
                  if (res.data === 'true') {
                  } else
                    require('toastr').error(
                      $filter('translate')('mail_writer.error')
                    );
                },
                function() {
                  gaDomUtils.hideGlobalLoader();
                }
              );
            });
          }
        };

        /**
         * send Email
         * @param type
         */
        var sendEmails = function(type) {
          var start = $filter('date')(
            scope.currentEvent.properties.start,
            'dd/MM/yyyy ' + $filter('translate')('calendar.email.at') + ' HH:mm'
          );
          var end = $filter('date')(
            scope.currentEvent.properties.end,
            'dd/MM/yyyy ' + $filter('translate')('calendar.email.at') + ' HH:mm'
          );
          var title =
            $filter('translate')('calendar.email.title') +
            scope.currentEvent.properties.title +
            ' ' +
            $filter('translate')('calendar.email.the') +
            ' ' +
            start;
          var recipients = [];
          var recipients_fullnames = [];
          var recipientsInvite = [];
          var recipientsInviteFullname = [];
          if (!scope.currentEvent.properties.description)
            scope.currentEvent.properties.description = '';
          if (scope.users_invite.length) {
            scope.users_invite.forEach(function(recipient) {
              if (recipient.email && recipient.email != '') {
                recipientsInvite.push(recipient.email);
              }
              recipientsInviteFullname.push(recipient.fullname);
            });
          }
          if (scope.users_concerne.length) {
            scope.users_concerne.forEach(function(recipient) {
              if (recipient.email && recipient.email != '') {
                recipients.push(recipient.email);
              }
              recipients_fullnames.push(recipient.fullname);
            });
          }

          var contentHead =
            '<p>' +
            $filter('translate')('calendar.email.hello') +
            ',</p>' +
            '<p>' +
            $rootScope.xgos.user.name +
            ' ' +
            $rootScope.xgos.user.vorname +
            ' ' +
            $filter('translate')('calendar.email.has') +
            ' ' +
            type +
            ' ' +
            $filter('translate')('calendar.email.event') +
            ' <b>' +
            scope.currentEvent.properties.title +
            '. </b></p>' +
            '<p>' +
            $filter('translate')('calendar.event.start') +
            ': <b>' +
            start +
            '</b></p>' +
            '<p>' +
            $filter('translate')('calendar.event.end') +
            ': <b>' +
            end +
            '</b></p>';

          if (
            scope.currentEvent.properties.description &&
            scope.currentEvent.properties.description != ''
          ) {
            contentHead =
              contentHead +
              '<p>' +
              $filter('translate')('calendar.event.detail') +
              ': ' +
              scope.currentEvent.properties.description +
              '</p>';
          }
          if (
            scope.currentEvent.properties.place &&
            scope.currentEvent.properties.place != ''
          ) {
            contentHead =
              contentHead +
              '<p>' +
              $filter('translate')('calendar.event.place') +
              ': ' +
              scope.currentEvent.properties.place +
              '</p>';
          }
          if (!recipients_fullnames.length) {
            contentHead =
              contentHead +
              '<p>' +
              $filter('translate')('calendar.email.noconcerne') +
              '</p>';
          } else {
            contentHead =
              contentHead +
              '<p>' +
              $filter('translate')('calendar.email.concernes') +
              ': ' +
              recipients_fullnames.join(', ') +
              '</p>';
          }

          if (recipientsInviteFullname.length) {
            contentHead =
              contentHead +
              '<p>' +
              $filter('translate')('calendar.email.invites') +
              ': ' +
              recipientsInviteFullname.join(', ') +
              '</p>';
          } else {
            contentHead =
              contentHead +
              '<p>' +
              $filter('translate')('calendar.email.noinvite') +
              '</p>';
          }

          if (scope.users_concerne.length) {
            prepareEmail(recipients, title, contentHead);
          }

          if (scope.users_invite.length) {
            var contentInvite =
              contentHead +
              '<p> <a class="btn-primary" href="' +
              $location.absUrl().split('#')[0] +
              '#/calendar_invite">' +
              $filter('translate')('calendar.email.manage') +
              '</a></p>';
            prepareEmail(recipientsInvite, title, contentInvite);
          }
        };
        /**
         * saveEvent
         */
        scope.currentEventRelation = {};
        scope.saveEvent = function() {
          var now = formatDate(new Date());
          scope.currentEvent.properties.creation_date = now;
          scope.currentEvent.properties.start = formatDate(scope.currentEvent.properties.start);
          scope.currentEvent.properties.end = formatDate(scope.currentEvent.properties.end);
          var features = {
            collection: {
              type: 'FeatureCollection',
              features: [
                {
                  type: 'Feature',
                  geometry: scope.currentEvent.geometry,
                  properties: scope.currentEvent.properties,
                },
              ],
            },
          };

          setEventRelations(features);
          setEventAlerts(features);
          setEventUsers(features);

          gaDomUtils.showGlobalLoader();

          CalendarFactory.addevent(features).then(
            function(res) {
              $timeout(function() {
                scope.uploadFileData.id = res.data[0].id;
              });
              if ($rootScope.xgos.portal.sendMailCfg)
                sendEmails($filter('translate')('calendar.email.created'));
              require('toastr').success(
                $filter('translate')(
                  'tools.calendar.ui.event_actions.save.done'
                ),
                {
                  positionClass: 'toast-bottom-left',
                }
              );

              $rootScope.$on('changeAttachmentId_ok', function() {
                scope.currentEvent = false;
                $rootScope.$broadcast('kis_calendar_event_refresh');
                $rootScope.$broadcast('closeEventModal');
                $rootScope.$broadcast('closeNgDialogAgendaCtrl');
                $rootScope.$broadcast('g2cAlertUpdate');
              });
              if (scope.onFinish && typeof scope.onFinish === 'function') {
                scope.onFinish({
                  insertedEvents: res.data,
                  eventData: angular.copy(scope.currentEvent),
                });
              }
              gaDomUtils.hideGlobalLoader();
            },
            function(res) {
              require('toastr').error(
                'Erreur lors de la planification de RDV',
                '',
                {
                  positionClass: 'toast-bottom-left',
                }
              );
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        /**
         * updateEvent
         */
        scope.updateEvent = function() {
          let idDossier = ""
          if (Array.isArray(scope.currentEventRelations.features)) { 
            scope.currentEventRelations.features.forEach((relation)=>{
              if (relation.properties.feature_id && relation.properties.feature_id.includes("kis_anc_dossier")
              && !relation.properties.feature_id.includes("kis_anc_dossier_controle")) {
                idDossier = relation.properties.feature_id.split('.')[1]
              }
            })
          }
          var start = moment(scope.currentEvent.properties.start);
          start = start.toISOString();
          start = $filter('date')(start, 'yyyy-MM-ddTHH:mm:ss.sssZ');
          scope.currentEvent.properties.start = start;

          var end = moment(scope.currentEvent.properties.end);
          end = end.toISOString();
          end = $filter('date')(end, 'yyyy-MM-ddTHH:mm:ss.sssZ');
          scope.currentEvent.properties.end = end;
          scope.currentEvent.properties.idDossier = idDossier;
          scope.currentEvent.properties.startTimeFormat = (new Date(start)).getTime();

          var features = {
            collection: {
              type: 'FeatureCollection',
              features: [scope.currentEvent],
            },
          };

          setEventRelations(features);
          setEventAlerts(features);
          setEventUsers(features);
          
          gaDomUtils.showGlobalLoader();
          CalendarFactory.updateevent(features).then(
            function(res) {
              if (scope.updateEmail.value) {
                if ($rootScope.xgos.portal.sendMailCfg)
                  sendEmails($filter('translate')('calendar.email.update'));
              }
              require('toastr').success(
                $filter('translate')(
                  'tools.calendar.ui.event_actions.update.done'
                ),
                {
                  positionClass: 'toast-bottom-left',
                }
              );

              $rootScope.$broadcast('kis_calendar_event_refresh');
              $rootScope.$broadcast('closeEventModal');
              $rootScope.$broadcast('g2cAlertUpdate');
              if (typeof scope.onFinish === 'function') {
                scope.onFinish({
                  insertedEvents: res.data,
                  eventData: angular.copy(scope.currentEvent),
                });
              }
              
              scope.currentEvent = false;
              kisCalendarFactory.refreshListeDossier()
              gaDomUtils.hideGlobalLoader();
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
            }
          );
        };
        scope.saveEventControle = function() {
          if (scope.addCtrl && scope.addCtrl.value == true) {
            $rootScope.$broadcast(
              'add_controle_to_dossier',
              scope.currentEvent.collection.features[0].properties.start
            );
          } else {
            var control = scope.controleevent;
            scope.savecurrentEventCtrl(control);
          }
        };

        $rootScope.$on('save_current_event_control', function(event, data) {
          if (scope.currentEvent && scope.currentEvent.linked_objects) {
            scope.currentEvent.linked_objects[0].features[0].properties.feature_id =
              data.control.id;
            scope.savecurrentEventCtrl(data.control);
          }
        });

        scope.savecurrentEventCtrl = function(control) {
          delete scope.currentEvent.collection.features[0]['id'];
          if (
            angular.isDefined(scope.currentEvent.linked_objects[0].features)
          ) {
            scope.currentEvent.linked_objects[0].features.forEach(function(
              elem,
              i
            ) {
              if (elem.properties.feature_uid == 'kis_anc_dossier')
                scope.currentEvent.linked_objects[0].features.splice(i, 1);
            });
          }
          control.properties.agent = scope.currentagent;
          control.properties.date_passage_rdv =
            scope.currentEvent.collection.features[0].properties.start;
          CalendarFactory.addevent(scope.currentEvent).then(
            function(res) {
              var eventid = res.data[0].id;
              //$rootScope.$broadcast("kis_calendar_event_refresh");
              scope.currentEvent = false;
              scope.currentevent = res.config.data.collection.features[0];
              scope.currentevent.id = eventid;

              var promise = AncAppFactory.updatecontrole({
                type: 'FeatureCollection',
                features: [control],
              });

              promise.then(
                function(res1) {
                  var xxx = {
                    event: scope.currentevent,
                    controle: res1.config.data.features[0],
                    agent: scope.currentagent,
                  };

                  $rootScope.$broadcast('kis_calendar_eventCtrl_refresh', xxx);
                  $rootScope.$broadcast('refresh_liste_controle');
                  $rootScope.$broadcast('closeNgDialogAgendaCtrl');

                  AncAppFactory.updateDatesDossier(control.id).then(function() {
                    kisCalendarFactory.refreshListeDossier();
                  });
                },
                function() {
                  require('toastr').error('error');
                }
              );

              require('toastr').success(
                "Évenement enregistré dans le calendrier de l'agent.",
                '',
                {
                  positionClass: 'toast-bottom-left',
                }
              );
            },
            function() {
              require('toastr').error(
                "Erreur lors de l'ajout de l'événement.",
                '',
                {
                  positionClass: 'toast-bottom-left',
                }
              );
            }
          );
        };
        scope.updateEventControle = function() {
          // console.log(scope.controleevent);
          scope.controleevent.properties.agent = scope.currentagent;
          scope.controleevent.properties.date_passage_rdv =
            scope.currentEvent.collection.features[0].properties.start;
          CalendarFactory.updateevent(scope.currentEvent).then(
            function(res) {
              scope.currentEvent = false;
              scope.currentevent = res.config.data.collection.features[0];
              // mise a jour du controle en fonctiond e l'event
              var promise = AncAppFactory.updatecontrole({
                type: 'FeatureCollection',
                features: [scope.controleevent],
              });
              promise.then(
                function(res1) {
                  var xxx = {
                    event: scope.currentevent,
                    controle: res1.config.data.features[0],
                    agent: scope.currentagent,
                  };
                  $rootScope.$broadcast('kis_calendar_eventCtrl_refresh', xxx);
                  $rootScope.$broadcast('closeNgDialogAgendaCtrl');
                  kisCalendarFactory.refreshListeDossier();
                  //ngDialog.close("agenda");
                },
                function() {
                  require('toastr').error('error');
                }
              );
              //var eventid = res.data[0].id;
              //require('toastr').success('ok');
            },
            function() {
              require('toastr').error('error');
            }
          );
        };

        /**
         * set Event alerts
         */
        var setEventAlerts = function(features) {
          if (scope.alerts.length) {
            features.alerts = [[]];
            for (var i = 0; i < scope.alerts.length; i++) {
              if (scope.alerts[i].type == 's') {
                features.alerts[0].push(scope.alerts[i].value);
              } else if (scope.alerts[i].type == 'm') {
                features.alerts[0].push(scope.alerts[i].value * 60);
              } else if (scope.alerts[i].type == 'h') {
                features.alerts[0].push(scope.alerts[i].value * 60 * 60);
              } else if (scope.alerts[i].type == 'd') {
                features.alerts[0].push(scope.alerts[i].value * 60 * 60 * 24);
              } else if (scope.alerts[i].type == 'w') {
                features.alerts[0].push(
                  scope.alerts[i].value * 60 * 60 * 24 * 7
                );
              } else if (scope.alerts[i].type == 'mth') {
                features.alerts[0].push(
                  scope.alerts[i].value * 60 * 60 * 24 * 30
                );
              }
            }
          }
        };

        /**
         * set Event users concerne and invite
         */
        var setEventUsers = function(features) {
          if (scope.users_concerne.length || scope.users_invite.length) {
            features.users = [[]];

            for (var i = 0; i < scope.users_concerne.length; i++) {
              features.users[0].push({
                login: scope.users_concerne[i].login,
                type: 'concerne',
              });
            }

            for (var i = 0; i < scope.users_invite.length; i++) {
              features.users[0].push({
                login: scope.users_invite[i].login,
                type: 'invite',
              });
            }
          }
        };

        /**
         * return wether an event is complete and can be submitted
         */
        scope.canSubmitEvent = function() {
          var res = true;
          scope.relationsInvalid = false;
          scope.dateInvalid = false;
          scope.valeursInvalid = false;
          if (
            scope.currentEventRelations &&
            scope.currentEventRelations.features &&
            scope.currentEventRelations.features.length
          ) {
            for (
              var i = 0;
              i < scope.currentEventRelations.features.length;
              i++
            ) {
              if (
                !scope.currentEventRelations.features[i].properties ||
                !scope.currentEventRelations.features[i].properties
                  .feature_uid ||
                scope.currentEventRelations.features[i].properties
                  .feature_uid == '' ||
                !scope.currentEventRelations.features[i].properties
                  .feature_id ||
                scope.currentEventRelations.features[i].properties.feature_id ==
                  ''
              ) {
                scope.relationsInvalid = true;
                res = false;
              }
            }
          }

          if (scope.currentEvent) {
            var start = new Date(scope.currentEvent.properties.start);
            var end = new Date(scope.currentEvent.properties.end);
            if (start > end) {
              res = false;
              scope.dateInvalid = true;
            }
          }

          var prop = scope.currentEvent.properties;
          if (
            angular.isUndefined(prop) ||
            angular.isUndefined(prop.title) ||
            angular.isUndefined(prop.start) ||
            angular.isUndefined(prop.end) ||
            angular.isUndefined(prop.type_evenement) ||
            prop.color == false
          ) {
            scope.valeursInvalid = true;
            res = false;
          }
          return res;
        };

        scope.blokTypeEventIfAnc = function() {
          // on ne bloque pas les nouveaux events
          if (!angular.isDefined(scope.currentEvent.id)) return false;

          var blokType = false;
          var eventType = scope.eventTypes[0].properties.type;
          if (eventType.startsWith('kis_anc')) {
            blokType = true;
          }
          return blokType;
        };

        /**
         * quand EventType changed, refresh alerts
         * @param currentEvent
         * @returns {boolean}
         */
        scope.currentEventTypeChange = function(currentEvent, type_id) {
          if(!currentEvent.properties.colorFromUser) {
            scope.currentEvent.properties.color = false;
            scope.eventTypes.forEach(function (eventType) {
              if (
                  eventType.properties.type_id == type_id &&
                  eventType.properties.default_color
              ) {
                scope.currentEvent.properties.color =
                    eventType.properties.default_color;
              }
            });
          }
          if (!scope.currentEvent.properties.color) {
            scope.currentEvent.properties.color = 'e74c3c';
          }
          if (currentEvent.id || $rootScope.xgos.user.login == 'root') {
            return false;
          }
          getAlerts(currentEvent);
        };

        /**
         * restrict_move_event
         * @returns {boolean}
         */
        scope.restrict_move_event = function() {
          var res = false;
          if (scope.eventTypes.length) {
            scope.eventTypes.forEach(function(type) {
              if (
                type.properties.type_id ==
                scope.currentEvent.properties.type_evenement
              ) {
                if (type.properties.restrict_move_event == true) {
                  res = true;
                }
              }
            });
          }
          if (!scope.currentEvent.id) res = false;
          return res;
        };

        /**
         * return alert type and value
         * @param value
         * @param type
         * @param renderType
         * @returns {*}
         */
        var returnAlertTypeOrValue = function(value, type, renderType) {
          if (value % (30 * 24 * 60 * 60) == 0) {
            type = 'mth';
            value = value / (30 * 24 * 60 * 60);
          } else if (value % (7 * 24 * 60 * 60) == 0) {
            type = 'w';
            value = value / (7 * 24 * 60 * 60);
          } else if (value % (24 * 60 * 60) == 0) {
            type = 'd';
            value = value / (60 * 24 * 60);
          } else if (value % (60 * 60) == 0) {
            type = 'h';
            value = value / (60 * 60);
          } else if (value % 60 == 0) {
            type = 'm';
            value = value / 60;
          }
          if (renderType == 'type') {
            return type;
          } else if (renderType == 'value') {
            return value;
          }
        };
        /**
         * get alerts
         * @param currentEvent
         */
        var getAlerts = function(currentEvent) {
          for (var i = 0; i < scope.eventTypes.length; i++) {
            if (
              scope.eventTypes[i].properties.type_id ==
              currentEvent.properties.type_evenement
            ) {
              scope.currentType = scope.eventTypes[i];
              scope.alerts = [];
              var tab = ['alerte1', 'alerte2', 'alerte3'];
              for (var j = 0; j < tab.length; j++) {
                var type = 'm';
                var value = scope.currentType.properties[tab[j]];

                if (scope.currentType.properties[tab[j]]) {
                  scope.alerts.push({
                    value: returnAlertTypeOrValue(value, type, 'value'),
                    type: returnAlertTypeOrValue(value, type, 'type'),
                  });
                }
              }
            }
          }
        };

        /**
         * add alert
         */
        scope.addAlert = function() {
          scope.alerts.push({
            value: 10,
            type: 'm',
          });
        };

        /**
         * remove alert
         * @param index
         */
        scope.removeAlert = function(index) {
          scope.alerts.splice(index, 1);
        };

        /**
         * remove all alerts
         */
        scope.removeAllAlerts = function() {
          var ans = confirm(
            'Êtes-vous certain de vouloir supprimer toutes les alertes ?'
          );
          if (ans) {
            scope.alerts = [];
          }
        };

        /**
         * checkbox for alerts
         * @type {*[]}
         */
        scope.alertDelaiTypes = [
          /*{
                    id: 's',
                    label: 'secondes'
                }, */ {
            id: 'm',
            label: 'minutes',
          },
          {
            id: 'h',
            label: 'heures',
          },
          {
            id: 'd',
            label: 'jours',
          },
          {
            id: 'w',
            label: 'semaines',
          },
          {
            id: 'mth',
            label: 'mois',
          },
        ];

        scope.panels = [
          { title: 'user' },
          { title: 'alerte' },
          { title: 'objet' },
          { title: 'document' },
        ];

        /**
         * render panel name
         * @param title
         * @returns {*}
         */
        scope.renderPanelName = function(title, attachmentNumber) {
          if (title == 'alerte') {
            // title = scope.alerts.length + ' ' + (scope.alerts && scope.alerts.length>1 ? title : title+'s');
            if (scope.alerts && scope.alerts.length) {
              if (scope.alerts.length == 1) {
                title =
                  '1 ' + $filter('translate')('calendar.event.alert_lowercase');
              } else {
                title =
                  scope.alerts.length +
                  ' ' +
                  $filter('translate')('calendar.event.alert_lowercase_plural');
              }
            } else {
              title =
                $filter('translate')('calendar.event.none_f') +
                ' ' +
                $filter('translate')('calendar.event.alert_lowercase');
            }
          } else if (title == 'objet') {
            if (
              scope.currentEventRelations &&
              scope.currentEventRelations.features.length
            ) {
              if (scope.currentEventRelations.features.length == 1) {
                title =
                  '1 ' + $filter('translate')('calendar.event.object_linked');
              } else {
                title =
                  scope.currentEventRelations.features.length +
                  ' ' +
                  $filter('translate')('calendar.event.objects_linked');
              }
            } else {
              title =
                $filter('translate')('calendar.event.none') +
                ' ' +
                $filter('translate')('calendar.event.object_linked');
            }
          } else if (title == 'user') {
            if (scope.users_invite.length || scope.users_concerne.length) {
              if (
                scope.users_invite.length + scope.users_concerne.length ==
                1
              ) {
                title = '1 ' + $filter('translate')('calendar.event.user');
              } else {
                title =
                  scope.users_invite.length +
                  scope.users_concerne.length +
                  ' ' +
                  $filter('translate')('calendar.event.users');
              }
            } else {
              title =
                $filter('translate')('calendar.event.none') +
                ' ' +
                $filter('translate')('calendar.event.user');
            }
          } else if (title == 'document') {
            if (!attachmentNumber) {
              title =
                $filter('translate')('calendar.event.none') +
                ' ' +
                $filter('translate')('calendar.event.document_linked');
            } else if (attachmentNumber <= 1) {
              title =
                attachmentNumber +
                ' ' +
                $filter('translate')('calendar.event.document_linked');
            } else {
              title =
                attachmentNumber +
                ' ' +
                $filter('translate')('calendar.event.documents_linked');
            }
          }
          return title;
        };

        /**
         * eventHasMap return whether event has map
         * @returns {boolean|*}
         */
        scope.eventHasMap = function() {
          return scope.map !== false;
        };

        function refreshControleur() {
          scope.users_concerne = [];
          scope.users_invite = [];
          if (!scope.currentEvent) {
            scope.users_concerne = [];
            scope.users_invite = [];
            return ;
          }
          CalendarFactory.getusersbyeventid(scope.currentEvent.id).then(
            function(res) {
              if (angular.isDefined(scope.currentEvent.id)) {
                scope.users_concerne = [];
                scope.users_invite = [];
                for (var i = 0; i < res.data.features.length; i++) {
                  for (var j = 0; j < scope.usersCol.length; j++) {
                    if (res.data.features[i].properties.type == 'concerne') {
                      if (
                        scope.usersCol[j].login ==
                        res.data.features[i].properties.user
                      ) {
                        scope.users_concerne.push(scope.usersCol[j]);
                      }
                    } else if (
                      res.data.features[i].properties.type == 'invite'
                    ) {
                      if (
                        scope.usersCol[j].login ==
                        res.data.features[i].properties.user
                      ) {
                        scope.users_invite.push(scope.usersCol[j]);
                      }
                    }
                  }
                }
                checkUserPermissions();
              }
            }
          );
        }

        scope.$watch('currentEvent', refreshControleur);
        /**
         * get liste users
         */
        UsersFactory.getactiveuserslight().then(function(res) {
          res.data.forEach(function(user) {
            user.url = 'img/user/default/user.png';
          });
          scope.usersCol = res.data;
          for (var i = 0; i < scope.usersCol.length; i++) {
            scope.usersCol[i].fullname =
              scope.usersCol[i].name + ' ' + scope.usersCol[i].vorname;
          }

          if (!scope.currentEvent.id) {
            addCurrentUserToConcerne();
          }
          refreshControleur();
        });

        /**
         * check string is email
         * @param email
         * @returns {boolean}
         */
        var validateEmail = function(email) {
          var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
          return re.test(email);
        };
        scope.usersExterneCol = [];
        scope.users_externe = [];
        scope.$watch(
          'users_externe',
          function() {
            if (scope.users_externe && scope.users_externe.length) {
              for (var i = 0; i < scope.users_externe.length; i++) {
                scope.users_externe[i].url = 'img/user/default/user.png';
                if (!validateEmail(scope.users_externe[i].email)) {
                  scope.users_externe.splice(i, 1);
                }
              }
            }
          },
          1
        );
        scope.users_concerne = [];
        scope.users_invite = [];
        /**
         * users_concerne changed
         */
        scope.$watch(
          'users_concerne',
          function(users_concerne) {
            addCurrentUserToConcerne();
            // Si le premier utilisateur concerné par l'évènement a une couleur,
            // l'évènement prend cette couleur (on enlève le #)
            if (users_concerne[0] && users_concerne[0].userHasColor) {
              scope.currentEvent.properties.color = users_concerne[0].userColor.substring(1);
              scope.currentEvent.properties.colorFromUser = true;
            } else {
              if (scope.currentEvent.properties){
                scope.currentEvent.properties.colorFromUser = false;
              }
            }
            checkusers(scope.users_concerne, scope.users_invite, 'invites');
          },
          1
        );

        /**
         *
         * @returns {boolean}
         */
        var addCurrentUserToConcerne = function() {
          if (
            !scope.currentUser ||
            (!scope.currentUser.login &&
              scope.currentEvent.properties.created_by !=
                scope.currentUser.login)
          ) {
            return false;
          }

          for (var i = 0; i < $rootScope.xgos.user.roles.length; i++) {
            if (
              $rootScope.xgos.user.roles[i].name == 'rootUser' ||
              $rootScope.xgos.user.roles[i].name == 'kis_calendar_manager' ||
              $rootScope.xgos.user.login == 'root'
            ) {
              return false;
            }
          }
          var contain = false;
          for (var i = 0; i < scope.users_concerne.length; i++) {
            if (scope.currentUser.login == scope.users_concerne[i].login) {
              contain = true;
            }
          }
          if (contain == false && scope.usersCol && scope.usersCol.length) {
            for (var j = 0; j < scope.usersCol.length; j++) {
              if (scope.usersCol[j].login == scope.currentUser.login) {
                scope.users_concerne.push(scope.usersCol[j]);
                checkUserPermissions();
              }
            }
          }
        };
        /**
         * users_invite changed
         */
        scope.$watch(
          'users_invite',
          function(users_invite) {
            checkusers(scope.users_invite, scope.users_concerne, 'concernes');
          },
          1
        );

        /**
         * check users
         * @param users
         */
        var checkusers = function(users, users_, type) {
          for (var i = 0; i < users.length; i++) {
            var contain = false;
            for (var j = 0; j < scope.usersCol.length; j++) {
              if (scope.usersCol[j].name == users[i].name) {
                contain = true;
                users[i] = scope.usersCol[j];
              }
            }
            if (contain == false) {
              users.splice(i, 1);
            }
          }

          contain = false;
          for (var i = 0; i < users_.length; i++) {
            if (users.length) {
              if (users_[i].login == users[users.length - 1].login) {
                contain = true;
              }
            }
          }
          if (contain == true) {
            if (
              !scope.currentEvent.properties.created_by ||
              scope.currentEvent.properties.created_by ==
                $rootScope.xgos.user.name
            ) {
              require('toastr').error(
                users[users.length - 1].fullname +
                  ' ' +
                  $filter('translate')('calendar.event.already_in_part') +
                  ' ' +
                  type
              );
            }
            users.splice(users.length - 1, 1);
          }
        };

        scope.openHistoriesDialog = function() {
          scope.currentFeatureUid = FeatureTypeFactory.getFeatureUidByName(
            'kis_calendar_event'
          );
          ngDialog.open({
            template:
              'js/XG/containers/views/modal.history.kis_calendar_event.html',
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
          });
        };

        /**
         * Annuler Event
         */
        scope.annulerEvent = function() {
          kisCalendarFactory.annulerEvent(
            scope.currentEvent.id,
            scope.closeEvent
          );
        };

        /**
         *  put end and start time auto
         */
        scope.$watch(
          'currentEvent.properties.start',
          function(start) {
            if (
              scope.currentEvent &&
              scope.currentEvent.properties.start &&
              !scope.currentEvent.id &&
              !scope.currentEvent.properties.end
            ) {
              scope.currentEvent.properties.end = $filter('date')(
                moment(scope.currentEvent.properties.start)
                  .add(1, 'hour')
                  .toDate(),
                'yyyy-MM-ddTHH:mm:ss.sssZ'
              );
            }
          },
          1
        );

        scope.updateEmail = {};

        $rootScope.$watch(
          'calendar.visible',
          function() {
            if ($rootScope.calendar.visible == true) {
              $rootScope.$broadcast('MapPositionPickerRemoveDraw');
              getMap();
            }
          },
          1
        );

        scope.positionpicker = {};

        scope.positionAutoComplete = {};
        /**
         * set position by positionAutoComplete
         */
        scope.$watch(
          'positionAutoComplete',
          function(positionAutoComplete) {
            if (positionAutoComplete.v) {
              if (angular.isDefined(positionAutoComplete.v.value)) {
                if (angular.isDefined(positionAutoComplete.v.geometry)) {
                  var feature;
                  if (scope.geocodage == 'google') {
                    feature = getFeatureByPoint([
                      positionAutoComplete.v.geometry.location.lng,
                      positionAutoComplete.v.geometry.location.lat,
                    ]);
                  } else if (scope.geocodage == 'nominatim') {
                    feature = getFeatureByPoint([
                      parseFloat(positionAutoComplete.v.lon),
                      parseFloat(positionAutoComplete.v.lat),
                    ]);
                  } else if (scope.geocodage.indexOf('kis_geocoder_') == 0) {
                    feature = getFeatureByPoint(
                      positionAutoComplete.v.geometry.coordinates
                    );
                  }
                  scope.currentEvent.geometry = feature.geometry;
                }

                scope.currentEvent.properties.place =
                  positionAutoComplete.v.value;
              } else {
                delete scope.currentEvent.geometry;
                scope.currentEvent.properties.place = positionAutoComplete.v;
              }
            }
          },
          1
        );

        /**
         * click MapPositionPicker
         */
        scope.openMapPositionPicker = function() {
          if (scope.canModifyEvent) $rootScope.calendar.visible = false;
        };

        /**
         * get feature geiJson by Point
         * @param coords
         */
        var getFeatureByPoint = function(coords) {
          var coords_3857 = ol.proj.transform(coords, 'EPSG:4326', 'EPSG:3857');

          var x = coords_3857[0];
          var y = coords_3857[1];
          var view = scope.map.getView();
          var resolution = view.getResolution();

          if (resolution != 'undefined') {
            var leftX = x - 5 * resolution;
            var rightX = x + 5 * resolution;
            var bottomY = y - 5 * resolution;
            var topY = y + 5 * resolution;
          } else {
            leftX = x - 5;
            rightX = x + 5;
            bottomY = y - 5;
            topY = y + 5;
          }

          var format = new ol.format.GeoJSON();
          /*      var feature = format.writeFeatureObject(new ol.Feature({
                        geometry: new ol.geom.MultiPolygon([[[coords_3857, coords_3857, coords_3857, coords_3857]]])
                    }));*/
          var feature = format.writeFeatureObject(
            new ol.Feature({
              geometry: new ol.geom.MultiPolygon([
                [
                  [
                    [leftX, bottomY],
                    [rightX, bottomY],
                    [rightX, topY],
                    [leftX, topY],
                    [leftX, bottomY],
                  ],
                ],
              ]),
            })
          );
          return feature;
        };
        /**
         * get position
         */
        scope.$watch(
          'positionpicker',
          function(positionpicker) {
            if (positionpicker.v && positionpicker.v.coordinates) {
              $rootScope.calendar.visible = true;
              $rootScope.$broadcast('MapPositionPickerRemoveDraw');
              var feature = getFeatureByPoint(positionpicker.v.coordinates);
              if (!scope.currentEvent) {
                scope.currentEvent = {};
              }
              scope.currentEvent.geometry = feature.geometry;
              if (
                scope.geocodage == 'google' &&
                positionpicker.v.infos[0] &&
                positionpicker.v.infos[0].formatted_address
              ) {
                scope.currentEvent.properties.place =
                  positionpicker.v.infos[0].formatted_address;
              } else if (
                scope.geocodage == 'nominatim' &&
                positionpicker.v.infos.display_name
              ) {
                scope.currentEvent.properties.place =
                  positionpicker.v.infos.display_name;
              } else if (
                scope.geocodage.indexOf('kis_geocoder_') == 0 &&
                positionpicker.v.infos.properties.label
              ) {
                scope.currentEvent.properties.place =
                  positionpicker.v.infos.properties.label;
              }
            }
          },
          1
        );
        /**
         * remove position
         */
        scope.deletePosition = function() {
          delete scope.currentEvent.geometry;
          scope.currentEvent.properties.place = '';
        };

        /**
         * centrer la position
         */
        var positionVectorLayer;
        scope.centerPosition = function() {
          scope.map.removeLayer(positionVectorLayer);
          $rootScope.calendar.visible = !$rootScope.calendar.visible;
          var feature = new ol.Feature({
            geometry: new ol.geom.MultiPolygon(
              scope.currentEvent.geometry.coordinates
            ),
          });

          var extent = feature.getGeometry().getExtent();

          var center = [extent[0], extent[1]];
          center = ol.proj.transform(
            center,
            'EPSG:3857',
            scope.map
              .getView()
              .getProjection()
              .getCode()
          );

          scope.map.getView().setCenter(center);
          scope.map.getView().setZoom(15);

          var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point(center),
            population: 4000,
            rainfall: 500,
          });
          var iconStyle = new ol.style.Style({
            image: new ol.style.Icon({
              src: 'img/widget/adressLocation/marker.png',
              scale: 1,
            }),
          });
          iconFeature.setStyle(iconStyle);

          positionVectorLayer = new ol.layer.Vector({
            source: new ol.source.Vector({
              features: [iconFeature],
            }),
          });
          scope.map.addLayer(positionVectorLayer);
        };

        /**
         * format date
         * @param dateSource
         * @returns {*}
         */
        var formatDate = function(dateSource) {
          var date = moment(dateSource);
          date = date.toISOString();
          date = $filter('date')(date, 'yyyy-MM-ddTHH:mm:ss.sssZ');
          return date;
        };

        scope.informEmail = false;
        var currentEventStart, currentEventEnd;
        if (scope.currentEvent.id) {
          currentEventStart = formatDate(scope.currentEvent.properties.start);
          currentEventEnd = formatDate(scope.currentEvent.properties.end);
        }

        /**
         * update event, date changed, inform email send auto
         */
        var currentStartTime = scope.currentEvent.properties.start;
        scope.$watch(
          'currentEvent.properties.start',
          function(start) {
            if (start) {
              currentStartTime = moment(start).format('yyyy-MM-ddTHH:mm:ss.sssZ');
            } else {
              if (!scope.currentEvent) return false;
              scope.currentEvent.properties.start = currentStartTime;
            }
            avertirEmail(currentEventStart, start);
          },
          1
        );
        var currentEndTime = scope.currentEvent.properties.end;
        scope.$watch(
          'currentEvent.properties.end',
          function(end) {
            if (end) {
              currentEndTime = moment(end).format('yyyy-MM-ddTHH:mm:ss.sssZ');
            } else {
              if (!scope.currentEvent) return false;
              scope.currentEvent.properties.end = currentEndTime;
            }
            avertirEmail(currentEventEnd, end);
          },
          1
        );
        var avertirEmail = function(currentData, date) {
          if (scope.currentEvent.id) {
            date = formatDate(date);
            if (currentData != date) {
              scope.informEmail = true;
              scope.updateEmail.value = true;
            } else {
              scope.informEmail = false;
            }
          }
        };

        function checkUserPermissions() {
          if (!scope.currentEvent || !scope.currentEvent.id) {
            scope.canModifyEvent = true;
            scope.historyIsActive = false;
            return;
          }

          scope.canModifyEvent = false;
          if (
            $rootScope.xgos.user.name ==
            scope.currentEvent.properties.created_by
          ) {
            scope.canModifyEvent = true;
          }

          if (
            Array.isArray(scope.users_concerne) &&
            scope.users_concerne.filter(user => user.login === $rootScope.xgos.user.login).length
          ) {
            scope.canModifyEvent = true;
          }

          for (var i = 0; i < $rootScope.xgos.user.roles.length; i++) {
            if (
              $rootScope.xgos.user.roles[i].name == 'kis_calendar_manager' ||
              $rootScope.xgos.user.login == 'root'
            ) {
              scope.canModifyEvent = true;
            }
            if (
              $rootScope.xgos.user.roles[i].name == 'rootUser' ||
              $rootScope.xgos.user.login == 'root'
            ) {
              if (
                gaJsUtils.checkNestedProperty(
                  'parameters.history.active',
                  $rootScope.xgos.portal
                )
              ) {
                scope.historyIsActive = true;
              }
            }
          }

          if (
            scope.currentEvent.properties.allow_external_modification == true
          ) {
            scope.canModifyEvent = true;
          }

          if (scope.cannotModify) {
            scope.canModifyEvent = false;
          }
        }
      },
    };
  };

  kisCalendarEvent.$inject = [
    'CalendarFactory',
    'gaDomUtils',
    '$filter',
    '$rootScope',
    '$location',
    '$anchorScroll',
    'UsersFactory',
    'authFactory',
    'ngDialog',
    'FeatureTypeFactory',
    'FunctionFactory',
    '$timeout',
    'gaJsUtils',
    'AncAppFactory',
    'kisCalendarFactory',
  ];
  return kisCalendarEvent;
});
