import { Component, OnInit, ViewChild, Inject, LOCALE_ID, Input } from '@angular/core';
import { CalendarComponent } from 'ionic2-calendar';
import { AlertController, ModalController } from '@ionic/angular';
import { formatDate } from '@angular/common';
import { EventsService } from 'src/app/services/events.service';
import { Event } from '../../models/event.model';
import { Router, NavigationEnd } from '@angular/router';
import { AlertService } from 'src/app/services/alert.service';
import { momentG }  from 'src/plugin/momentG';
import { DomSanitizer } from "@angular/platform-browser";
import { EventPerson } from 'src/app/models/eventperson.model';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'

// showTimeline
import { setHours, setMinutes } from 'date-fns';
import {
  CalendarDateFormatter,
  CalendarEvent,
  CalendarView,
  DAYS_OF_WEEK,
} from 'angular-calendar';
import { CustomDateFormatter } from './custom-date-formatter.provider';
import { NewEventPage } from './new-event/new-event.page';
import { AuthService } from 'src/app/services/auth.service';
import { LoginUserRespose } from 'src/app/models/user.model';
import { DateAdapter } from '@angular/material/core';
import { ToastService } from 'src/app/services/toast.service';
import { eventSource } from 'src/app/models/agenda/eventSource';
import { eventListBox as eventListBoxComponent } from './eventListBox'
import { CalendarService } from 'src/app/store/calendar.service';

@Component({
  selector: 'app-agenda',
  templateUrl: './agenda.page.html',
  styleUrls: ['./agenda.page.scss'],
  providers: [
    {
      provide: CalendarDateFormatter,
      useClass: CustomDateFormatter,
    },
  ],
})
export class AgendaPage implements OnInit {

  view: CalendarView = CalendarView.Day;

  viewDate: Date = new Date();

  weekStartsOn: number = DAYS_OF_WEEK.MONDAY;

  weekendDays: number[] = [DAYS_OF_WEEK.FRIDAY, DAYS_OF_WEEK.SATURDAY];

  CalendarView = CalendarView;

  timelineDate: string;

  contacts:  EventPerson[]

  setView(view: CalendarView) {
    this.view = view;
  }

  // calendar
  showCalendar: boolean;
  calendarHeight: string;

  // for timeline
  events: CalendarEvent[] = [];
  TimelinePR:  CalendarEvent[] = [];
  TimelinePRList = {}
  TimelineMD: CalendarEvent[] = [];
  TimelineMDList = {}

  showTimelinePR = false;
  showTimelineMD = false;

  // timeline filter
  timelineFilterState: string = 'Todos';
  showTimelineFilterState: boolean;
  showTimeline=true;

  /* List of events of our calendar */
  eventSource : eventSource[]  = []

  /* The title of the calendar */
  viewTitle: string;

  calendar = {
    /* Se the view of the calendar to a month view */
    mode: 'month',
    currentDate: new Date(),
  };

  selectedDate: Date;
  eventSelectedDate: Date = new Date();
  eventSelectedDate2: Date;

  rangeStartDate: Date;
  rangeEndDate: Date;

  selectedEvent: Event;
  selectedEventId: string | number;
  postEvent: any;

  // temporary data
  taskParticipants: any = [];
  taskParticipantsCc: any = [];
  adding: "intervenient" | "CC" = "intervenient";

  @ViewChild(CalendarComponent) myCal: CalendarComponent;

  segment:  "Combinado" |  "Pessoal" | "Oficial" = "Combinado";
  timelineSedment : "Combinado" |  "Pessoal" | "Oficial";

  profile:'mdgpr' | 'pr';

  // this will make  toggle add event and.
  showEventEditOrOpen:  "edit" | "add" | "" | "eventoToApprove" = ""
  prEventList: Event[];
  mdEventList: Event[];

  showLoader: boolean;

  startTime: Date;
  endTime: Date;

  eventListBoxComponent = new eventListBoxComponent()

  mobileComponent = {
    showAddNewEvent: false,
    showEditEvent: false,
    showEventDetails: false,
    showEventList: false,
    transparentEventList: false,
    transparentEventToApprove: false,
    showEventToApprove: false,
    showAttendees: false,
    showAttendeeModal: false,
    showEditEventToApprove: false,
  }

  eventToaprove: any = {
    back: false,
    serialNumber: "",
    saveData: {}
  }

  /**
   * @description determinant if edit or add event component is open
   */
  IsEvent: "edit" | "add" | "view";
  viewingEventObject:  CalendarEvent ;
  loggeduser: LoginUserRespose;

  constructor(
    private alertCtrl: AlertController,
    @Inject(LOCALE_ID) private locale: string,
    private modalCtrl: ModalController,
    private eventService: EventsService,
    private router: Router,
    private alertController: AlertService,
    private sanitizer: DomSanitizer,
    authService: AuthService,
    private dateAdapter: DateAdapter<any>,
    private toastService: ToastService,
    public calendarService: CalendarService
    ) {
    this.dateAdapter.setLocale('es');

    this.locale = 'pt'

    this.loggeduser = authService.ValidatedUser;

    this.calendarHeight = "320px";
    this.showCalendar = true;
    this.timelineDate = momentG(new Date(),'dd MMMM yyyy');

    this.showLoader = false;
    this.showTimelineFilterState = false;
    this.showTimeline = false;

    if(this.loggeduser.Profile == 'MDGPR') {
      this.mobileComponent.showEventList = true;
    }

    setTimeout(()=>{
      try {
        this.myCal.update();
        this.myCal.loadEvents();
      } catch(e) {}

      this.updateEventListBox()

    }, 1000)

  }

  ngOnInit() {

    this.profile = "mdgpr";

    const pathname = window.location.pathname

    let realoadCounter = 0

    this.router.events.forEach((event) => {

      if(event instanceof NavigationEnd && event.url == pathname ) {

        if (this.segment == null) {
          this.segment = "Combinado";
        }
        if ( realoadCounter != 0) {

          this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);

        }
        realoadCounter++;
      }

    });

    window.onresize = (event) => {
      // if not table remove all component
      if( window.innerWidth <= 1024){
        this.cloneAllmobileComponent();
      }
    };

  }

  //Go to the next view of the calendar month/week/day
  next() {
    this.myCal.slideNext();
    this.myCal.loadEvents();
    this.myCal.update();
  }
  //Go to the previous view of the calendar
  back(){
    this.myCal.slidePrev();
    this.myCal.loadEvents();
    this.myCal.update();
  }
  //Shows the title of your view
  onViewTitleChanged(title){
    this.viewTitle = title;
  }

  // show information about the clicked event in timeline
  eventClicked(event : CalendarEvent): void {
  /*     console.log('Event clicked', event); */
    //clear

    this.setIntervenient([]);
    this.setIntervenientCC([]);
    this.clearPostEvent();

    this.IsEvent= "view";

    this.viewingEventObject = event;

    this.eventSelectedDate =  event.start;
    this.selectedEventId = event.id;

    this.cloneAllmobileComponent();


    this.showEventEditOrOpen = 'edit';

    if( window.innerWidth <= 1024) {
      this.viewEventDetail(event.id)
      //this.router.navigate(["/home/agenda", event.id, 'agenda']);
    } else {
      this.cloneAllmobileComponent();

      this.mobileComponent.showEventDetails = true;
    }

  }


  //Show information of the event
  async onEventSelected(ev: { event: Event}){

    this.router.navigate(["/home/agenda", ev.event.EventId, 'agenda']);
  }

  onCurrentChanged = (ev: Date) => {
    // timeline change date
    this.timelineDate = momentG(new Date(ev),'dd MMMM yyyy');
    this.viewDate = new Date(ev);
    // calendar change date
    this.eventSelectedDate = new Date(ev);

  };

  // changedate
  dropDownChangeDate(id: string){
    /* const currentCandarDayYear = formatDate(this.eventSelectedDate,'dd -- yyyy', 'pt');
    const newDate = new Date(currentCandarDayYear.replace('--',id));
    this.onCurrentChanged(newDate); */
  }

  onTimeSelected = (ev: { selectedTime: Date, events: any[] }) => {
    // console.log('Selected time: ' + ev.selectedTime + ', hasEvents: ' + (ev.events !== undefined && ev.events.length !== 0));
    this.eventSelectedDate2 = ev.selectedTime;
  }

  onRangeChanged (ev: { startTime: Date, endTime: Date }) {
    this.rangeStartDate = ev.startTime;
    this.rangeEndDate = ev.endTime;

    this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);


    try {
      this.myCal.update();
      this.myCal.loadEvents();
    } catch(e) {}

    this.updateEventListBox()

  }

  // for calendar
  currentDayEventDisplayBorder(day: any, id: any) {

    const events = day[id].events;

    if (events.length == 0) {

      return "";

    } else if (events.length >= 1) {

      let classs = [];

      events.forEach(element => {

        const profile_ = element.profile == 'md'? 'mdgpr': 'pr';
        const eventtype = element.event.CalendarName;


        // if (startTimeSamp < endTimeSamp && endDay == 29  && (endMinutes + endHours) == 0) {
        //   // console.log(id, (endMinutes + endHours))
        //   classs.push(`calendar-event-border`);
        // }

        classs.push(`calendar-event-border calendar-${profile_}-event-type-${eventtype}`);

      });

      return classs.join(' ');
    }

    return "";
  }

  // for timeline

  get CalendarCurrentDay ():any {

    /* console.log(this.viewDate.getDate(), '0_0') */
    // console.log(this.viewDate.getDate(), '0_0')

    return this.viewDate.getDate()
  }

  // for timeline
  timelineIsCurrentDate(): Boolean {
    return momentG(new Date(),'dd MMMM yyyy', 'pt') == momentG(this.eventSelectedDate,'dd MMMM yyyy', 'pt');
  }

  momentG(date, formate , wgs) {
    return momentG(date, formate , wgs)
  }


  // for timeline
  timelineFilter(calendarName, eventsList, profile){

    this.timelineFilterState = calendarName;

    // remove all event
    let events = [];

    this.showTimelineFilterState = false;

    eventsList.forEach((element, eventIndex) => {

      // timeline start
      const startHours =  new Date(element.StartDate).getHours().toLocaleString();
      const EndHours = new Date(element.EndDate).getHours().toLocaleString();

      events.push({
        start: setHours(setMinutes(new Date(element.StartDate), 0), parseInt(startHours)),
        end: setHours(setMinutes(new Date(element.EndDate), 0), parseInt(EndHours)),
        color: {
          primary: '#0000',
          secondary: '#0000'
        },
        id: element.EventId,
        index: eventIndex,
        profile: profile,
        CalendarName: element.CalendarName,
        event: element,
        Subject: element.Subject
      });

    });

    return events;
  }

  eventFilter() {}

  TimelineDayEvent(day): string {
    return (day).padStart(2, '0') +' '+this.viewTitle
  }

  get calendarDay(): string {

    return ((new Date(this.timelineDate)).getDate()).toString().padStart(2,'0')
  }

  EventTretment ({startTime, endTime}) {

    const startTimeSamp = new Date(startTime).toLocaleDateString()
    const endTimeSamp = new Date(endTime).toLocaleDateString()

    const endMinutes = new Date(endTime).getMinutes()
    const endHours = new Date(endTime).getHours()


    if (startTimeSamp < endTimeSamp  && (endMinutes + endHours) == 0) {
      endTime = new Date(endTime);
      endTime.setSeconds(endTime.getSeconds() - 1);
      return new Date(endTime)
    } else {
      return new Date(endTime)
    }

  }

  loadRangeEvents(startTime: Date, endTime: Date) {

    this.showLoader = true;

    if(window.innerWidth < 800){

      // this.showTimeline = false;

      switch (this.segment) {
        case "Combinado":
          //Inicializa o array eventSource

          if(this.profile == "mdgpr" && this.loggeduser.Profile == 'MDGPR' ) {
            this.eventService.getAllMdEvents( momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59') ).then(

              (response:any) => {
                console.log(response);


                // calendar
                this.calendarService.removeRange(startTime, endTime, 'md')

                // loop
                this.calendarService.pushEvent(response, 'md');

                this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'md', this.rangeStartDate, this.rangeEndDate, 'date')

                this.myCal.update();
                this.myCal.loadEvents();

                this.showLoader = false;
                this.showTimeline = true;

            }).finally(()=>{
              this.showLoader = false;
            })

          }
          else if(this.profile == "pr" && this.loggeduser.Profile == 'MDGPR') {

            this.eventService.getAllSharedEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then((response:any) => {

              this.calendarService.removeRange(startTime, endTime, 'pr')
              // calendar
              this.calendarService.pushEvent(response, 'pr');

              this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')

              this.myCal.update();
              this.myCal.loadEvents();

              this.showLoader = false;
              this.showTimeline = true;

              }).finally(()=>{
                this.showLoader = false;
              })

          }
          else if(this.loggeduser.Profile == 'PR') {
            this.eventService.getAllPrEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then(
              (response:any) => {

                // calendar
                // this.eventSource=[];

                // clear the current month only
                this.calendarService.removeRange(startTime, endTime, 'pr')

                this.calendarService.pushEvent(response, 'pr');


                this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')


                this.myCal.update();
                this.myCal.loadEvents();

                this.showLoader = false;
                this.showTimeline = true;


              }).finally(()=>{
                this.showLoader = false;
              })
          }
        break;

        case "Pessoal":
          //Inicializa o array eventSource
          if(this.profile == "mdgpr" && this.loggeduser.Profile == 'MDGPR') {
            this.eventService.getAllMdPessoalEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then((response:any) => {

              this.calendarService.removeRange(startTime, endTime, 'md')

              const eventsList = response.filter(data => data.CalendarName == "Pessoal");
              // loop
              this.calendarService.pushEvent(eventsList, 'md');


              this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'md', this.rangeStartDate, this.rangeEndDate, 'date')

              this.myCal.update();
              this.myCal.loadEvents();

              this.showLoader = false;
              this.showTimeline = true;
            }).finally(()=>{
              this.showLoader = false;
            })

          }
          else{
            this.eventService.getAllPrEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then((response:any) => {
              //this.eventSource=[];

              // clear the current month only
              this.calendarService.removeRange(startTime, endTime, 'pr')

              const eventsList = response.filter(data => data.CalendarName == "Pessoal");
              this.calendarService.pushEvent(eventsList, 'pr');


              this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')


              this.myCal.update();
              this.myCal.loadEvents();

              this.showLoader = false;
              this.showTimeline = true;

            }).finally(()=>{
              this.showLoader = false;
            })
          }
          break;

        case "Oficial":

          //Inicializa o array eventSource
          const eventsList = [];

          if(this.profile == "mdgpr" && this.loggeduser.Profile == 'MDGPR') {
            this.eventService.getAllMdEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then((res:any) => {

              this.calendarService.removeRange(startTime, endTime, 'md')

              const eventsList = res.filter(data => data.CalendarName == "Oficial");

              this.calendarService.pushEvent(eventsList, 'md');


                this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'md', this.rangeStartDate, this.rangeEndDate, 'date')

                this.myCal.update();
                this.myCal.loadEvents();

                this.showLoader = false;
                this.showTimeline = true;

              }).finally(()=>{
                this.showLoader = false;
              })
          } else {
            this.eventService.getAllPrEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then((res:any) => {

              // this.eventSource=[];

              this.calendarService.removeRange(startTime, endTime, 'pr')

              const  eventsList = res.filter(data => data.CalendarName == "Oficial");
              this.calendarService.pushEvent(eventsList, 'pr');


              this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')

              this.myCal.update();
              this.myCal.loadEvents();

              this.showLoader = false;
              this.showTimeline = true;

            }).finally(()=>{
              this.showLoader = false;
            })
          }
          break;

      }
    } else {
      // calendar

      let counter = 0;

      if(this.loggeduser.Profile == 'MDGPR') {

        this.eventService.getAllMdEvents( momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59') ).then( (response:any) => {

          let eventsList  = response;

          this.calendarService.removeRange(startTime, endTime, 'md')

          // loop
          this.calendarService.pushEvent(eventsList, 'md');

          this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'md', this.rangeStartDate, this.rangeEndDate, 'date')

          this.myCal.update();
          this.myCal.loadEvents();

          this.showTimelineMD = true;

          counter++;
          if(counter==2) {
            this.showLoader = false;
          }


        }).finally(()=> {
          counter++;
          if(counter==2) {
            this.showLoader = false;
          }
        })

        this.eventService.getAllSharedEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then((response:any) => {

          let eventsList = response;

          // clear the current month only
          this.calendarService.removeRange(startTime, endTime, 'pr')

          this.calendarService.pushEvent(eventsList, 'pr');

          this.TimelinePRList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')

          this.myCal.update();
          this.myCal.loadEvents();

          this.showTimelinePR = true;

          counter++;

          if(counter==2 || this.loggeduser.Profile == 'PR') {
            this.showLoader = false;
          }

        }).finally(()=>{
          counter++;
          if(counter==2) {
            this.showLoader = false;
          }
        })

      } else {

      this.eventService.getAllPrEvents(momentG(new Date(startTime),'yyyy-MM-dd HH:mm:ss'), momentG(new Date(endTime),'yyyy-MM-dd 23:59:59')).then((response:any) => {

        let eventsList;
        if(this.segment == 'Oficial') {
          eventsList = response.filter(data => data.CalendarName == "Oficial");
        } else if (this.segment == 'Pessoal') {
          eventsList = response.filter(data => data.CalendarName == "Pessoal");
        } else {
          eventsList = response;
        }

        // clear the current month only
        this.calendarService.removeRange(startTime, endTime, 'pr')

        this.calendarService.pushEvent(eventsList, 'pr');

        this.TimelinePRList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')


        this.myCal.update();
        this.myCal.loadEvents();

        this.showTimelinePR = true;

        counter++;

        if(counter==1 || this.loggeduser.Profile == 'PR') {
          this.showLoader = false;
        }

      }).finally(()=>{
        if(counter==1 || this.loggeduser.Profile == 'PR') {
          this.showLoader = false;
        }
      })

    }

    }
  }

  updateEventListBox() {

    this.TimelinePRList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')
    this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'md', this.rangeStartDate, this.rangeEndDate, 'date')

  }

  eventListBox(list, nice?) {
    let days = {};

    list.forEach( (event:any)=> {

      var startDate: any = new Date(event.start);

      var endDate: any = this.EventTretment({
        startTime: startDate,
        endTime: event.end
      })

      const day = (((new Date (event.start)).getDate())).toString().padStart(2,'0')

      event.manyDays = false


      event.todayOnly = new Date(event.start).toLocaleDateString() == new Date(event.end).toLocaleDateString()



      if(!days.hasOwnProperty(day)) {
        days[day] = []
      }

      if (new Date(startDate).toLocaleDateString() != new Date(endDate).toLocaleDateString()) {

        // difference
        const diffTime = Math.abs(endDate - startDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        if (diffDays <= 150 && !event.event.IsAllDayEvent  ) {


          if (diffDays >= 1) {

            const StartEvent =  Object.assign({}, {
              title: event.title,
              start: event.start,
              end: event.end,
              color: event.color,
              id: event.id,
              index: event.index,
              profile: event.profile,
              CalendarName: event.CalendarName,
              event: {
                Subject: event.event.Subject,
                StartDate:  event.event.StartDate,
                EndDate: event.event.EndDate,
                Location:  event.event.Location,
                EventId:  event.event.EventId,
                CalendarName: event.event.CalendarName
              },
              startMany: true,
              endMany: false,
              middle: false
            })

            days[day].push(StartEvent)

            let i = 1;

            while (startDate.getFullYear() !=  endDate.getFullYear() ||
              startDate.getMonth() != endDate.getMonth() ||
              startDate.getDate() != endDate.getDate()) {

              const newDate = startDate.setDate(startDate.getDate()+ i)

              let otherDays =   (((new Date (newDate)).getDate())).toString().padStart(2,'0')

              event.other = true

              event.start = newDate
              if(!days.hasOwnProperty(otherDays)) {

                days[otherDays] = []
              }

              if (!(startDate.getFullYear() !=  endDate.getFullYear() ||
              startDate.getMonth() != endDate.getMonth() ||
              startDate.getDate() != endDate.getDate())) {
                // last push

                const EndEvent =  Object.assign({}, {
                  title: event.title,
                  start: event.start,
                  end: event.end,
                  color: event.color,
                  id: event.id,
                  index: event.index,
                  profile: event.profile,
                  CalendarName: event.CalendarName,
                  event: {
                    Subject: event.event.Subject,
                    StartDate:  event.event.StartDate,
                    EndDate: event.event.EndDate,
                    Location:  event.event.Location,
                    EventId:  event.event.EventId,
                    CalendarName: event.event.CalendarName
                  },
                  Subject: event.Subject,
                  startMany: false,
                  endMany: true,
                  middle: false
                })

                days[otherDays].push(EndEvent)

              } else {
                const EndEvent =  Object.assign({}, {
                  title: event.title,
                  start: event.start,
                  end: event.end,
                  color: event.color,
                  id: event.id,
                  index: event.index,
                  profile: event.profile,
                  CalendarName: event.CalendarName,
                  event: {
                    Subject: event.event.Subject,
                    StartDate:  event.event.StartDate,
                    EndDate: event.event.EndDate,
                    Location:  event.event.Location,
                    EventId:  event.event.EventId,
                    CalendarName: event.event.CalendarName
                  },
                  Subject: event.Subject,
                  startMany: false,
                  endMany: true,
                  middle: true
                })
                days[otherDays].push(EndEvent)
              }

            }

          } else {
            days[day].push(event)

          }
        } else {
          days[day].push(event)

        }

      }

      days[day].push(event)

    })

    setTimeout(()=>{
      document.querySelectorAll('.EventListBox-container .EventListBox').forEach((e)=>{
        if(e.childElementCount == 0) {
          e.parentElement.style.display = 'none'
        } else {
          e.parentElement.style.display = 'block'
        }
      })
    }, 10)

    return days
  }

  get viewEventMonth () {
    return  this.viewDate.getMonth()
  }

  dateMonth(event: any) {
    return  new Date(event.start).getMonth()
  }

  eventListVisible(event) {
    return momentG(event,'MMMM yyyy')  ==  momentG(this.calendar.currentDate, 'MMMM yyyy')
  }


  actions(){}

  doRefresh(ev: any){
    this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
    setTimeout(() => {
      ev.target.complete();
    }, 250)
  }

  showAlert() {
    this.alertController.presentAlert("Funcionalidade em desenvolvimento.");
  }

  changeProfile() {

    if(this.profile == "mdgpr") {
      this.profile ="pr";
      this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
      this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'pr', this.rangeStartDate, this.rangeEndDate, 'date')

    }
    else {
      this.profile ="mdgpr";
      this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
      this.TimelineMDList = this.eventListBoxComponent.list(this.calendarService.eventSource, 'md', this.rangeStartDate, this.rangeEndDate, 'date')
    }

  }

  async openAddEvent() {

    await this.cloneAllmobileComponent();

    this.showEventEditOrOpen = 'add';
    this.IsEvent = 'add';

    if( window.innerWidth <= 1024){
      const modal = await this.modalCtrl.create({
        component: NewEventPage,
        componentProps:{
          segment: this.segment,
          profile: this.profile,
          eventSelectedDate: this.eventSelectedDate
        },
        cssClass: 'modal  modal-desktop',
        backdropDismiss: false
      });
      await modal.present();
      modal.onDidDismiss().then((data) => {
        if(data){

        }
        this.openAddEventDismiss(data['data'])
      });
    } else {
      this.mobileComponent.showAddNewEvent = true;
    }
  }


  openEditEvent(){
    this.showEventEditOrOpen = 'edit';

  }

  openAddEventDismiss(data){

    let postEvent: Event = data;
    if (postEvent.Subject != null)
    {
      // this.eventSource.push({
      //   title: postEvent.Subject,
      //   startTime: new Date(postEvent.StartDate),
      //   endTime: new Date(postEvent.EndDate),
      //   allDay: false,
      //   event: postEvent
      // });
      this.myCal.update();
      this.myCal.loadEvents();
      this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
    }

    this.cloneAllmobileComponent();
  }

  // open component
  async viewEventDetail(eventId:any) {

    this.router.navigate(['/home/agenda', eventId, 'agenda']);
    /* console.log(this.profile);

    const modal = await this.modalCtrl.create({
      component: ViewEventPage,
      componentProps:{
        eventId: eventId,
        adding: this.adding
      },
      cssClass: 'modal  modal-desktop',
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then((res)=>{
      if(res){
        // this.viewEventDetailDismiss(res);
      }
    }); */
  }

  // open component
  async viewEventDetailDismiss(data) {

    await this.cloneAllmobileComponent()

    if (data.type == 'edit') {

      this.selectedEvent = data.event;
      this.postEvent = data.event;

      this.mobileComponent.showEditEvent = true;

    }

    this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
  }


  // called from this template and child event
  async viewEventsToApprove() {
    await this.cloneAllmobileComponent();

    if( window.innerWidth <= 801) {
      this.router.navigate(['/home/agenda/event-list']);
    } else {
      // hide all components
      this.cloneAllmobileComponent();
      this.mobileComponent.transparentEventList = false;
      this.mobileComponent.showEventList = true;
    }
  }

  approveEventDismissGoBack() {

    window['temp.path:/shared/agenda/edit-event-to-approve.ts'] = {}

    this.cloneAllmobileComponent()

    this.mobileComponent.showEventToApprove = true;
    this.mobileComponent.showEditEventToApprove = false

  }

  approveEventDismiss({saveData, serialNumber, action}) {

    window['temp.path:/shared/agenda/edit-event-to-approve.ts'] = {}

    if(action == 'Aprovar') {
      this.eventToaprove = {
        back: true,
        saveData: saveData,
        serialNumber:serialNumber,
        action: action,
        InstanceId: saveData.workflowInstanceDataFields.InstanceId || ""
      }

      this.mobileComponent.showEventToApprove = true;
      this.mobileComponent.showEventList = false

    }

    this.showEventEditOrOpen = "eventoToApprove"
  }

  closeEventToApprove() {
    if (this.eventToaprove.back ==true && this.mobileComponent.showEventList ==true) {
      this.mobileComponent.transparentEventList = false;
      this.mobileComponent.showEventToApprove = false;
      this.eventToaprove.back = false;

    }
    else {

      this.mobileComponent.showEventToApprove = false;
      this.mobileComponent.showEventList = false;
    }

  }

  closeEventToApproveGoBack() {
    if( window.innerWidth <= 801){
      this.router.navigate(['/home/agenda/event-list']);
    } else {
      // hide all components
      this.cloneAllmobileComponent();
      this.mobileComponent.transparentEventList = false;
      this.mobileComponent.showEventList = true;
    }
  }

  // called from emitters
  /** @description open component to edit event to approve */
  EditApproveEventDismiss() {
    this.cloneAllmobileComponent();
    this.mobileComponent.showEditEventToApprove = true;
  }

  async cloneAllmobileComponent() {

    this.mobileComponent.showAddNewEvent = false;
    this.mobileComponent.showEditEvent = false;
    this.mobileComponent.showEventDetails = false;
    this.mobileComponent.showEventList = false;
    this.mobileComponent.showEventToApprove = false;
    this.mobileComponent.showAttendees = false;
    this.mobileComponent.showAttendeeModal = false;
    this.mobileComponent.showEditEventToApprove = false;

    this.closeEventToApprove();
  }

  async AproveEventEditEvent(data) {
    this.postEvent =data;
    this.mobileComponent.transparentEventToApprove= true;
    this.mobileComponent.showAddNewEvent = true;
  }

  // open component
  async openAttendeesComponent(data) {

    this.adding = data.type

    this.cloneAllmobileComponent();
    this.mobileComponent.showAttendees = true;
  }

  async clearContact() {
    this.contacts = [];
  }

  async setContact(data:EventPerson[]) {
    this.contacts = data;
  }

  async openAttendeeModal(){
    this.cloneAllmobileComponent();
    this.mobileComponent.showAttendeeModal = true;
  }


  async GoBackEditOrAdd() {

    if(this.showEventEditOrOpen == "edit") {
      this.cloneAllmobileComponent();

      this.mobileComponent.showEditEvent = true;
    } else if(this.showEventEditOrOpen == "add") {
      this.cloneAllmobileComponent();

      this.mobileComponent.showAddNewEvent = true;
    } else if(this.showEventEditOrOpen == "eventoToApprove") {
      this.cloneAllmobileComponent();
      this.mobileComponent.showEditEventToApprove = true
    }
    else {
      // do Nothings
    }

  }

  async closeComponentEditEventOrAdd() {

    if(this.IsEvent ='edit') {
      this.eventClicked(this.viewingEventObject);
    } else if (this.IsEvent = 'add') {
      this.cloneAllmobileComponent();
    }
  }

  async EventToApproveGoBack() {

  }

  async setIntervenient(data) {
    this.taskParticipants = removeDuplicate(data)

  }

  async setIntervenientCC(data) {
    this.taskParticipantsCc = removeDuplicate(data)
  }

  // Emitters
  // adding
  async setAdding(adding:  "intervenient" | "CC" = "intervenient") {
    this.adding =  adding;
  }

  async clearPostEvent(){
    this.postEvent = false;
  }

  async changeSegment(segments: "Combinado" |  "Pessoal" | "Oficial") {
    this.segment =  segments;

    if(segments=='Combinado'){
      this.timelineFilterState = 'Todos'
    } else {
      this.timelineFilterState = segments
    }
    this.showTimelineFilterState = false;

    setTimeout(()=>{
      document.querySelectorAll('.EventListBox-container .EventListBox').forEach((e)=>{
        if(e.childElementCount == 0) {
          e.parentElement.style.display = 'none'
        } else {
          e.parentElement.style.display = 'block'
        }
      })
    }, 10)


    setTimeout(()=>{
      document.querySelectorAll('.EventListBox-container .EventListBox').forEach((e)=>{
        if(e.childElementCount == 0) {
          e.parentElement.style.display = 'none'
        } else {
          e.parentElement.style.display = 'block'
        }
      })
    }, 100)

  }

  async showEventBox(event) {

    if ( event.event.CalendarName == this.segment || this.segment == 'Combinado') {
      return true
    }

    return false
  }


  shoeEventDay(events: any[]) {

    if ( this.segment == 'Combinado') {
      return true;
    }

    const reuslt = events.filter((e)=> e.CalendarName == this.segment)

    return reuslt.length != 0
  }

}
