import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { EventBody } from 'src/app/models/eventbody.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { EventsService } from 'src/app/services/events.service';
import { Event } from 'src/app/models/event.model';
import { AlertController } from '@ionic/angular';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { SearchPage } from 'src/app/pages/search/search.page';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { Attachment } from 'src/app/models/attachment.model';
import { ToastService } from 'src/app/services/toast.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import * as moment from 'moment';

@Component({
  selector: 'app-edit-event',
  templateUrl: './edit-event.page.html',
  styleUrls: ['./edit-event.page.scss'],
})

export class EditEventPage implements OnInit {

  stEvent: Event;
  isRecurring:string;
  isEventEdited: boolean;
  loadedEvent: Event;
  initCalendarName: string;
  eventBody: EventBody;
  segment:string = "true";
  eventAttendees: EventPerson[];
  // minDate: string;
  loadedEventAttachments: Attachment[]=[];
  recurringTypes: any;
  public dateControlOccurrence = new FormControl(moment("DD MM YYYY hh"));

  public date: any;
  public disabled = false;
  public showSpinners = true;
  public showSeconds = false;
  public touchUi = false;
  public enableMeridian = false;
  public minDate = new Date().toISOString().slice(0,10)
  public endMinDate = new Date(new Date().getTime() + 15 * 60000).toISOString().slice(0,10)
  public maxDate: any;
  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;

  Form: FormGroup;
  validateFrom = false

  @Input() taskParticipants: EventPerson[];
  @Input() taskParticipantsCc: EventPerson[];
  @Input() profile:string;
  @Input() selectedSegment: string;
  @Input() postEvent: Event;
  @Output() clearContact = new EventEmitter<any>();

  @Output() openAttendeesComponent = new EventEmitter<any>();
  @Output() closeComponent = new EventEmitter<any>();

  @Output() setIntervenient = new EventEmitter<any>();
  @Output() setIntervenientCC = new EventEmitter<any>();
  @Output() clearPostEvent = new EventEmitter<any>();

  public dateControlStart = new FormControl(moment("DD MM YYYY hh"));
  public dateControlEnd = new FormControl(moment("DD MM YYYY hh"));

  showLoader = false

  get dateStart () {
    return this.dateControlStart.value
  }

  get dateEnd () {
    return this.dateControlEnd.value
  }

  @ViewChild('picker') picker: any;
  @ViewChild('fim') fim: any;
  @ViewChild('inicio') inicio: any;
  @ViewChild('picker1') picker1: any;

  public options = [
    { value: true, label: 'True' },
    { value: false, label: 'False' }
  ];

  get dateOccurrence () {
    return this.dateControlOccurrence.value
  }
  public listColors = ['primary', 'accent', 'warn'];
  public stepHours = [1, 2, 3, 4, 5];
  public stepMinutes = [1, 5, 10, 15, 20, 25];
  public stepSeconds = [1, 5, 10, 15, 20, 25];

  constructor(
    private modalController: ModalController,
    private eventsService: EventsService,
    public alertController: AlertController,
    private attachmentsService: AttachmentsService,
    private toastService: ToastService ) {

  }

  ngOnInit() {
    this.dateControlOccurrence = new FormControl(moment(this.postEvent.EventRecurrence.LastOccurrence));

    if(!this.restoreTemporaryData()) {
      // clear

      if(this.postEvent) {
        if( this.postEvent.Body){
          if(typeof(this.postEvent.Body.Text) == 'string'){
            this.postEvent.Body.Text = this.postEvent.Body.Text.replace(/<[^>]+>/g, '');
          }
        }
      }

      // attendees list
      if(this.postEvent.Attendees != null) {
        this.postEvent.Attendees.forEach(e =>{
          if(e.IsRequired) {
            this.taskParticipants.push(e);
          } else {
            this.taskParticipantsCc.push(e);
          }
        })
      }

      this.taskParticipants = removeDuplicate(this.taskParticipants);
      this.taskParticipantsCc = removeDuplicate(this.taskParticipantsCc);

      this.setIntervenient.emit(this.taskParticipants);
      this.setIntervenientCC.emit(this.taskParticipantsCc);

      this.isEventEdited = false;

      if(this.postEvent.IsRecurring == false) {
        this.isRecurring = "Não se repete";
      }
      else{
        this.isRecurring = "Repete";
      }
    }

    this.getAttachments(this.postEvent.EventId);

    this.restoreDatepickerData();
    this.getRecurrenceTypes();

    this.postEvent.EventRecurrence.Type = this.postEvent.EventRecurrence.Type.toString();
    setTimeout(() => {
      this.postEvent.EventRecurrence.Type = this.postEvent.EventRecurrence.Type.toString();
      console.log( this.postEvent.EventRecurrence.Type);
    }, 1000);


  }

  close() {
    this.closeComponent.emit();
    this.setIntervenient.emit([]);
    this.setIntervenientCC.emit([]);
    this.clearContact.emit();

    this.deleteTemporaryData();
  }

  getRecurrenceTypes() {
    this.eventsService.getRecurrenceTypes().subscribe(res=>{
      console.log(res);
      this.recurringTypes = res;
    });
  }


  runValidation() {
    this.validateFrom  = true
  }

  injectValidation() {

    if (typeof(this.postEvent.EventRecurrence.Type) == 'number') {
      const str: any = this.postEvent.EventRecurrence.Type.toString()
      this.postEvent.EventRecurrence.Type = str
    }
    
    this.Form = new FormGroup({
      Subject: new FormControl(this.postEvent.Subject, [
        Validators.required,
        // Validators.minLength(4)
      ]),
      Location: new FormControl(this.postEvent.Location, [
        Validators.required,
      ]),
      CalendarName: new FormControl(this.postEvent.CalendarName),
      Categories: new FormControl(this.postEvent.Category, [
        Validators.required
      ]),
      dateStart: new FormControl(this.dateStart, [
        Validators.required
      ]),
      dateEnd: new FormControl(this.dateEnd, [
        Validators.required
      ]),
      dateOccurrence: new FormControl(this.dateOccurrence, [
        Validators.required
      ]),
      participantes: new FormControl(this.taskParticipants, [
        // Validators.required
      ]),
      Date: new FormControl( new Date(this.dateControlStart.value).toLocaleString() < new Date(this.dateControlEnd.value).toLocaleString()? 'ok': null,[
        Validators.required
      ]),

    })
  }

  openInicio() {
    let input: any = document.querySelector('#new-inicio')
    if(input) {
      console.log(input)
      input.click()
    }
  }

  openFim() {
    let input: any = document.querySelector('#new-fim')
    if(input) {
      input.click()
    }
  }

  openLastOccurrence() {
    let input: any = document.querySelector('#last-occurrence')
    if(input) {
      input.click()
    }
  }

  onSelectedRecurringChanged(ev:any){
    console.log(ev);
    if(ev.length > 1){
      console.log(ev.filter(data => data != '-1'));
      this.postEvent.EventRecurrence.Type = ev.filter(data => data != '-1');
    }
    if(ev.length == 0){
      this.postEvent.EventRecurrence.Type = "-1";
    }
  }


  async save() {

    this.injectValidation()
    this.runValidation()

    if(this.Form.invalid) {
      return false
    }

    this.getDatepickerData()
    this.postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc);

    if(!this.postEvent.EventRecurrence.hasOwnProperty('Type')) {
      this.postEvent.EventRecurrence.Type = '-1'
    }

    //
    if(this.postEvent.EventRecurrence.Type == undefined) {
      this.postEvent.EventRecurrence.Type = '-1'
    }

    this.showLoader = true;

    await this.eventsService.editEvent(this.postEvent, 2, 3).subscribe(async () => {
      if(this.initCalendarName != this.postEvent.CalendarName) {
        let body = {
          "EventId": this.postEvent.EventId,
          "CalendarDestinationName": this.postEvent.CalendarName,
        }

        try {
          await this.eventsService.changeAgenda(body).toPromise();
        } catch (e) {}
      }
      this.showLoader = false;
      this.toastService.successMessage()
    },
    error => {
      this.showLoader = false
      this.toastService.badRequest()
    });

    this.clearPostEvent.emit();
    this.deleteTemporaryData();
    this.close();

    this.saveDocument()
  }


  saveDocument() {

    this.loadedEventAttachments.forEach((e)=>{

      const id: any = e.Id
      const remove = e['remove']

      if ( id == 'add') {
        //data.selected
        const DocumentToSave = {
          SourceTitle: e.SourceName,
          ParentId: this.postEvent.EventId,
          Source: '1',
          SourceId: e.SourceId,
          ApplicationId: e.ApplicationId.toString(),
          Id: '0',
          Link: '',
          SerialNumber: '',
        };

        this.attachmentsService.setEventAttachmentById(DocumentToSave).subscribe(()=>{
          this.getAttachments(this.postEvent.EventId);
        });

      } else if(remove) {
        this.attachmentsService.deleteEventAttachmentById(e.Id).subscribe( res=> {})
      }

    })

  }

  async addParticipants() {

    this.saveTemporaryData();

    this.openAttendeesComponent.emit({
      type: "intervenient"
    });

    this.clearContact.emit();
  }

  async addParticipantsCc() {

    this.saveTemporaryData();

    this.openAttendeesComponent.emit({
      type: "CC"
    });

    this.clearContact.emit();
  }


  getDatepickerData() {
    if (this.postEvent) {
      this.postEvent.StartDate = this.dateStart
      this.postEvent.EndDate = this.dateEnd
      this.postEvent.EventRecurrence.LastOccurrence = this.dateOccurrence
    }
  }

  restoreDatepickerData() {
    if (this.postEvent) {
      this.dateControlStart = new FormControl(moment(this.postEvent.StartDate));
      this.dateControlEnd = new FormControl(moment(this.postEvent.EndDate));
    }
  }

  saveTemporaryData() {

    this.getDatepickerData()

    window['temp.path:/home/agenda/edit-event.component.ts'] = {
      postEvent: this.postEvent,
      eventBody: this.eventBody,
      segment: this.segment
    }
  }

  restoreTemporaryData(): boolean {

    const restoredData =  window['temp.path:/home/agenda/edit-event.component.ts']

    if(JSON.stringify(restoredData) != "{}" && undefined != restoredData){
      this.postEvent = restoredData.postEvent
      this.eventBody = restoredData.eventBody
      this.segment = restoredData.segment

      this.restoreDatepickerData()

      return true;
    } else {
      return false;
    }

  }

  deleteTemporaryData(){
    window['temp.path:/home/agenda/edit-event.component.ts'] = {}
  }

  getAttachments(eventId: string){
    this.attachmentsService.getAttachmentsById(eventId).subscribe(res=>{
      this.loadedEventAttachments = res;
      console.log('res', res);
    });
  }

  deleteAttachment(attachmentID: string, index) {

    const id: any = this.loadedEventAttachments[index].Id

    if(id == 'add') {
      this.loadedEventAttachments = this.loadedEventAttachments.filter((e,i)=> i!=index)
    } else {
      this.loadedEventAttachments[index]['remove'] = true
    }

  }

  async getDoc() {

    const modal = await this.modalController.create({
      component: SearchPage,
      cssClass: 'modal-width-100-width-background modal',
      componentProps: {
        type: 'AccoesPresidenciais & ArquivoDespachoElect',
        showSearchInput: true,
        select: true,
      }
    });
    await modal.present();
    modal.onDidDismiss().then( async (res)=>{
      if(res){
        const data = res.data;

        const ApplicationIdDocumentToSave: any = {
          SourceName: data.selected.Assunto,
          ParentId: this.postEvent.EventId,
          SourceId: data.selected.Id,
          Stakeholders: false,
          ApplicationId: data.selected.ApplicationType.toString(),
          CreateDate: false,
          // needed to attach this document
          Id: 'add',
          SourceTitle: data.selected.Assunto,
          Source: '1',
          Link: '',
          SerialNumber: '',
        }

        console.log( this.loadedEventAttachments)
        this.loadedEventAttachments.push(ApplicationIdDocumentToSave)


      }
    });
  }


}
