'use strict';
define(() => {
  const kisCalendarFilters = (
    gaDomUtils,
    CalendarFactory,
    $location,
    kisCalendarFactory,
    UsersFactory,
    $rootScope,
    $timeout,
    $filter
  ) => {

    const kisCalendarFiltersRwLink = (scope) => {

      const agentsPlaceholder = 'Tous les Agents';
      const creatorPlaceholder = 'Tous les Créateurs';
      const eventTypesPlaceholder = 'Tous les types d\'événements';

      scope.$watch('rdvAllowedEventTypes', () => {
        scope.showAddEvent = scope.rdvAllowedEventTypes && scope.rdvAllowedEventTypes.length && scope.showAddEventButton;
      }, true);

      scope.$watch('eventTypes', () => {
        scope.filterEventTypes = [{properties: { type_id: eventTypesPlaceholder, alias: eventTypesPlaceholder}}];
        scope.filterEventTypes = scope.filterEventTypes.concat(angular.copy(scope.eventTypes));
      }, true);

      initFilters();

      scope.modelOptions = {
        debounce: { default: 500 }
      }

      scope.calendarComments = {};

      scope.agents = scope.agents || [];
      scope.creators = scope.creators || [];

      setCalendarUrls();

      getInvitedEvents();

      scope.toggleView = () => {
        scope.viewType = scope.viewType !== 'calendar' ? 'calendar' : 'list';
        scope.onChangeViewType({ viewType: scope.viewType });
      }

      scope.toggleFilters = () => {
        if (scope.showFilters == true) {
          initFilters();
          scope.onChangedFilters({ eventsFilters: scope.eventsFilters });
          scope.showFilters = false;
          return;
        }
        scope.showFilters = true;
      }

      scope.toggleView();

      scope.changeFilters = (form, eventsFilters) => {
        if (!form.$valid) { return; }
        scope.onChangedFilters({ eventsFilters });
      }

      scope.toggleEventTitle = () => {
        scope.showDescription = !scope.showDescription;
        changeViewDetails();
      };

      scope.toggleEventNumber = () => {
        scope.showNumber = !scope.showNumber;
        changeViewDetails();
      }

      scope.exportCalendarPdf = () => {
        gaDomUtils.showGlobalLoader();
        CalendarFactory.exportcalendarpdf()
          .then(downloadICalendar)
          .catch(() => require('toastr').error('Le téléchargement Pdf a échoué'))
          .finally(() => gaDomUtils.hideGlobalLoader());
      };

      new Clipboard('.exportCalendarBtn');
      scope.clickOnUpload = () => {
        require('toastr').success(
          $filter('translate')('calendar.export.copy_success'),
          { positionClass: 'toast-bottom-left' }
        );
        $timeout(function() {
          angular.element('#hiddendownloadIcalUrl').trigger('click');
        });
      }

      scope.exportICalendar = () => {
        gaDomUtils.showGlobalLoader();
        CalendarFactory.exporticalendar()
          .then(downloadICalendar)
          .catch(() => require('toastr').error('Le téléchargement Ics a échoué'))
          .finally(() => gaDomUtils.hideGlobalLoader());
      };

      scope.addNewEvent = () => {
        scope.onAddNewEvent();
      }

      scope.openInvitePage = function () {
        scope.invitedevents = [];
        var url = $location.absUrl().split('#')[0] + '#/calendar_invite';
        window.open(url);
      };

      scope.commentChanged = function () {
        CalendarFactory.saveComment(
          scope.calendarComments.value,
          scope.commentType,
          scope.commentDate
        );
      };

      scope.$watch('calendarView.type', (newType) => {
        switch (newType) {
          case 'agendaDay':
          case 'agendaWeek':
            scope.showComments =
              kisCalendarFactory.resources.config.showComment &&
              kisCalendarFactory.resources.config.showComment[
                newType
              ];
            getComment();
            break;
          default:
            scope.showComments = false;
        }
      });
      scope.$watch('calendarView.start', () => {
        if (scope.showComments) {
          getComment();
        }
      });

      function getInvitedEvents() {
        CalendarFactory.getinvitedevents().then(function (res) {
          scope.invitedevents = res.data.features;
        });
      }

      function initFilters() {
        scope.eventsFilters = {
          agent: agentsPlaceholder,
          created_by: creatorPlaceholder,
          type_evenement: eventTypesPlaceholder,
        };
      }

      function downloadICalendar(res) {
        if (!res || !res.data) { return require('toastr').error('Download failed! Please try again later'); }
        const resources = res.data.split(',');
        window.open(
          '/services/' + resources[0] + '/calendar/downloadICalendar?' +
          '&name=' + resources[1] +
          '&token=' + localStorage.getItem('auth_token')
        );
      }

      function setCalendarUrls() {
        const url = $rootScope.xgos.kis_public_url || '';
        const services = url.endsWith('/') ? 'services/' : '/services/';
        const baseUrl = url + services + $rootScope.xgos.portal.uid;
        const userUid = $rootScope.xgos.user.uid || 'rootUser';
        scope.downloadIcalUrl = `${baseUrl}/calendar/downloadICalendarFile?uid=${userUid}`;
      }

      function changeViewDetails() {
        scope.onChangeViewDetails({ details: { showDescription: scope.showDescription, showNumber: scope.showNumber } });
      }

      function getComment() {
        const commentDate = new Date();
        scope.commentType = scope.calendarView.type;
        commentDate.setDate(scope.calendarView.start.date());
        commentDate.setMonth(scope.calendarView.start.month());
        commentDate.setYear(scope.calendarView.start.year());
        commentDate.setHours(12);
        commentDate.setMinutes(0);
        commentDate.setSeconds(0);
        commentDate.setMilliseconds(0);
        scope.commentDate = commentDate.getTime();
        CalendarFactory.getComment(scope.calendarView.type, scope.commentDate).then(
          function (res) {
            scope.calendarComments.value = res.data;
          }
        );
      }

      // Récupération de la légende pour les types d'évènement
      const eventTypesColorLegend = [];
      if (Array.isArray(scope.eventTypes)) {
        for(const eventType of scope.eventTypes) {
          eventTypesColorLegend.push({
            name: eventType.properties.alias || eventType.properties.type,
            color: '#'+(eventType.properties.default_color || 'e74c3c')
          });
        }
      }
      
      // Récupération de la légende pour les couleurs des utilisateurs
      const usersColorLegend = [];
      UsersFactory.getLightUsersByRoles('').then(res => {
        for (const userWithColor of res.data) {
          if (userWithColor.userHasColor === true) {
            usersColorLegend.push({
              name: userWithColor.vorname,
              color: userWithColor.userColor
            })
          }
        }
      });

      // Le composant kis_calendar_legend_color est utilisé pour les deux légendes
      // On affecte donc colorLegends en fonction de la légende désirée
      scope.openColorLegend = (legendType) => {
        scope.colorLegends = [];
        if (legendType === 'Users') {
          scope.colorLegends = usersColorLegend;
        } else if (legendType === 'eventTypes') {
          scope.colorLegends = eventTypesColorLegend;
        }
      };
    }

    return {
      templateUrl: 'js/XG/containers/views/kis_calendar_filters.html',
      restrict: 'E',
      scope: {
        onChangedFilters: '&',
        onChangeViewType: '&',
        onAddNewEvent: '&',
        onChangeViewDetails: '&',
        eventTypes: '=?',
        rdvAllowedEventTypes: '=?',
        showDescription: '=?',
        disableDescription: '=?',
        showNumber: '=?',
        showAddEvent: '=?',
        showAddEventButton: '=?',
        viewType: '=?',
        agents: '=?',
        creators: '=?',
        calendarView: '=?'
      },
      link: kisCalendarFiltersRwLink
    }
  }

  kisCalendarFilters.$inject = [
    'gaDomUtils',
    'CalendarFactory',
    '$location',
    'kisCalendarFactory',
    'UsersFactory',
    '$rootScope',
    '$timeout',
    '$filter',
  ];
  return kisCalendarFilters;

});
