import { Component, OnInit, ViewChild, Inject, LOCALE_ID } from '@angular/core';
import { CalendarComponent } from 'ionic2-calendar';
import { AlertController, ModalController, Platform } from '@ionic/angular';
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 { CalendarStore } from 'src/app/store/calendar.service';
import { ListBoxService } from 'src/app/services/agenda/list-box.service';
import { ChangeProfileService } from 'src/app/services/change-profile.service';

import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service';
import { ThemeService } from 'src/app/services/theme.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;

  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;

  monthNum;
  yearNum;

  dropdownScrollWeal = false
  CalendarStore = CalendarStore
  listToPresent
  array = []

  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,
    private listBoxService: ListBoxService,
    private changeProfileService: ChangeProfileService,
    private sqliteservice: SqliteService,
    private platform: Platform,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService
  ) {

    this.dateAdapter.setLocale('es');
    this.locale = 'pt'

    this.loggeduser = authService.ValidatedUser;

    this.changeProfileService.registerCallback(() => {
      this.tigerUpdate()
      if (this.loggeduser.Profile == 'MDGPR') {
        this.mobileComponent.showEventList = true;
        this.profile = "mdgpr";
      } else {
        this.profile = "pr";
      }
    })

    if (this.loggeduser.Profile == 'MDGPR') {
      this.mobileComponent.showEventList = true;
      this.profile = "mdgpr";
    } else {
      this.profile = "pr";
    }

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

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


    this.tigerUpdate()

    window['year'] = this.changeYear

  }

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

      this.updateEventListBox()

    }, 1000)
  }

  ngOnInit() {

    //this.getFromDB();

    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++;
      }
    });

    this.backgroundservice.registerBackService('Online', () => {
      //this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
    });

    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.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.monthNum = new Date(ev).getMonth()
    this.yearNum = new Date(ev).getFullYear()

    this.viewDate = new Date(ev);
    // calendar change date
    this.eventSelectedDate = new Date(ev);

    this.updateEventListBox()

  };

  onDropDownScrollWeal() {

    setTimeout(() => {
      document.querySelector('.dropdown-scroll-weel').querySelectorAll('.active')[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
      setTimeout(() => {
        document.querySelector('.dropdown-scroll-weel').querySelectorAll('.active')[1].scrollIntoView({ behavior: 'smooth', block: 'center' });
      }, 300)
    }, 10)

  }

  // 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 {

    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.array = [];

    this.rangeStartDate = startTime
    this.rangeEndDate = endTime

    this.showLoader = true;

    if (window.innerWidth < 800) {

      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('ALL MD EVENTS', response);

            this.addEventToDB(response, "md");

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

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

            console.log('CALENDAR STORE', this.CalendarStore.eventSource)
            this.listToPresent = this.CalendarStore.eventSource
            this.trasnformData(response, 'md');

            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'md', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

            console.log('check list to present data', this.listToPresent);
            this.myCal.update();
            this.myCal.loadEvents();

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

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

      }
      // view PR calendar with MDGPR profile
      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.addEventToDB(response, "pr");

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

          this.listToPresent = this.CalendarStore.eventSource


          this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

          console.log('check list to present data', this.listToPresent);
          this.myCal.update();
          this.myCal.loadEvents();

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

        }).catch((error) => {
          this.getFromDB()
        })
          .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) => {
            console.log('ALL EVENT PR', response)
            this.addEventToDB(response, "pr");

            // clear the current month only
            // response == september
            // startTime = 1, endTime = 31
            this.CalendarStore.removeRange(startTime, endTime, 'pr')
            this.CalendarStore.pushEvent(response, 'pr');

            this.listToPresent = this.CalendarStore.eventSource


            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

            console.log('check list to present data', this.listToPresent);

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

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


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

    } else {
      // Desktop only

      let counter = 0;

      // view MDGPR calendar with MDGPR profile 
      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) => {

          this.addEventToDB(response, "md");
          let eventsList = response;

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

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

          this.listToPresent = this.CalendarStore.eventSource

          this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'md', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

          console.log('check list to present data', this.listToPresent);
          this.myCal.update();
          this.myCal.loadEvents();

          this.showTimelineMD = true;

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


        }).catch((error) => {
          this.getFromDB()
        })
          .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) => {

          this.addEventToDB(response, "pr");
          let eventsList = response;

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


          this.CalendarStore.pushEvent(eventsList, 'pr');
          this.listToPresent = this.CalendarStore.eventSource


          this.TimelinePRList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

          console.log('check list to present data', this.listToPresent);

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

          this.showTimelinePR = true;

          counter++;

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

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

      } else {

        // view PR calendar with PR profile
        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.addEventToDB(response, "pr");
          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.CalendarStore.removeRange(startTime, endTime, 'pr')

          this.CalendarStore.pushEvent(eventsList, 'pr');
          this.listToPresent = this.CalendarStore.eventSource

          this.TimelinePRList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })


          console.log('check list to present data', this.listToPresent);
          this.myCal.update();
          this.myCal.loadEvents();

          this.showTimelinePR = true;

          counter++;

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

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

      }

    }
  }

  trasnformData(response, profile) {
    console.log('Transform ', response)
    response.forEach(element => {
      let event = {
        startTime: new Date(element.StartDate),
        endTime: new Date(element.EndDate),
        allDay: false,
        event: element,
        calendarName: element.CalendarName,
        profile: profile,
        id: element.EventId,
      }
      this.array.push(event)
    });
    this.listToPresent = this.array;
    console.log('LIST TO PRESET', this.listToPresent)
  }

  //Deve ser removido para ficar só um method transform
  trasnformDataDB(response) {
    console.log('Transform ', response)
    response.forEach(element => {
      let event = {
        startTime: new Date(element.StartDate),
        endTime: new Date(element.EndDate),
        allDay: false,
        event: element,
        calendarName: element.CalendarName,
        profile: element.Profile,
        id: element.EventId,
      }
      this.array.push(event)
    });
    this.listToPresent = this.array;
    console.log('LIST TO PRESET', this.listToPresent)
  }

  addEventToDB(response, profile) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      if (response.length > 0) {

        response.forEach(element => {
          let event = {
            CalendarId: element.CalendarId,
            CalendarName: element.CalendarName,
            EndDate: element.EndDate,
            EventId: element.EventId,
            HasAttachments: element.HasAttachments,
            HumanDate: element.HumanDate,
            IsAllDayEvent: element.IsAllDayEvent,
            Location: element.Location,
            StartDate: element.StartDate,
            Subject: element.Subject,
            Profile: profile
          }
          this.sqliteservice.addEvent(event)

        });
      }
    }
  }

  getFromDB() {
    console.log('ALL EVENTS FROM DB AGENDA OFFLINE')
    this.sqliteservice.getAllEvents().then((events: any[]) => {
      console.log('ALL EVENTS FROM DB', events)
      let eventArray = [];

      this.trasnformDataDB(events)
      this.updateEventListBox()

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

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


    })
  }

  updateEventListBox() {

    if (window.innerWidth < 800) {

      switch (this.segment) {
        case "Combinado":

          if (this.profile == "mdgpr" && this.loggeduser.Profile == 'MDGPR') {
            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'md', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

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

            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

          }
          else if (this.loggeduser.Profile == 'PR') {
            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })
          }
          break;

        case "Pessoal":
          //Inicializa o array eventSource
          if (this.profile == "mdgpr" && this.loggeduser.Profile == 'MDGPR') {
            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'md', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

          }
          else {
            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })
            this.TimelinePRList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })
          }
          break;

        case "Oficial":

          if (this.profile == "mdgpr" && this.loggeduser.Profile == 'MDGPR') {
            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'md', this.rangeStartDate, this.rangeEndDate, {segment: this.segment, selectedDate: this.eventSelectedDate})

          } else {
            this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })
            this.TimelinePRList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

          }
          break;

      }
    } else {
      this.TimelinePRList = this.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })
      this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'md', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

    }

  }

  changeYear = (year) => {
    const a = this.calendar.currentDate

    const isInvalidDate = (dateString) => JSON.stringify(new Date(dateString)) === 'null';

    const newDate = new Date(year, a.getMonth(), a.getDay());

    if (!(isInvalidDate(newDate))) {
      this.calendar.currentDate = newDate

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

      this.updateEventListBox()
    } else {
      console.log('not valid ' + a)
    }


  }

  changeMonth = (month) => {
    const a = this.calendar.currentDate;
    console.log(a)

    const isInvalidDate = (dateString) => JSON.stringify(new Date(dateString)) === 'null';

    const newDate = new Date(a.getFullYear(), month, a.getDay());

    if (!(isInvalidDate(newDate))) {
      this.calendar.currentDate = newDate

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

      this.updateEventListBox()
    } else {
      console.log('not valid ' + a)
    }
  }


  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.listBoxService.list(this.listToPresent, 'pr', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })

    }
    else {
      this.profile = "mdgpr";
      this.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
      this.TimelineMDList = this.listBoxService.list(this.listToPresent, 'md', this.rangeStartDate, this.rangeEndDate, { segment: this.segment, selectedDate: this.eventSelectedDate })
    }

  }

  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;

    this.taskParticipants = []
    this.taskParticipantsCc = []
  }

  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.loadRangeEvents(this.rangeStartDate, this.rangeEndDate);
      this.eventClicked(this.viewingEventObject);
    } else if (this.IsEvent = 'add') {
      this.cloneAllmobileComponent();
    }
  }

  async EventToApproveGoBack() {

  }

  async setIntervenient(data) {

    setTimeout(() => {
      this.taskParticipants = removeDuplicate(data)
    }, 10)

  }

  async setIntervenientCC(data) {
    setTimeout(() => {
      this.taskParticipantsCc = removeDuplicate(data)
    }, 10)

  }

  // 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;


    // THIS LINE
    this.updateEventListBox()


  }


  shoeEventDay(events: any[]) {

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

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

    return reuslt.length != 0
  }

}
