import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AlertController, ModalController } from '@ionic/angular';
import * as moment from 'moment';
import { Attachment } from 'src/app/models/attachment.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { SearchList } from 'src/app/models/search-document';
import { SearchPage } from 'src/app/pages/search/search.page';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { EventsService } from 'src/app/services/events.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { ToastService } from 'src/app/services/toast.service';
import { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { EventToApproveEdit } from 'src/app/models/event.model';
import { ThemeService } from 'src/app/services/theme.service'


const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
  parse: {
    dateInput: "YYYY-MMMM-DD HH:mm"
  },
  display: {
    dateInput: "DD MMM YYYY H:mm",
    monthYearLabel: "MMM YYYY",
    dateA11yLabel: "LL",
    monthYearA11yLabel: "MMMM YYYY"
  }
}

@Component({
  selector: 'app-edit-event-to-approve',
  templateUrl: './edit-event-to-approve.page.html',
  styleUrls: ['./edit-event-to-approve.page.scss'],
})
export class EditEventToApprovePage implements OnInit {
  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);
  public maxDate: any;
  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;
  public dateControlStart = new FormControl(moment("DD MM YYYY hh"));
  public dateControlEnd = new FormControl(moment("DD MM YYYY hh"));
  recurringTypes: any;
  selectedRecurringType: any;

  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;

  loadedAttachments: Attachment[]= []

  eventProcess = {
    serialNumber: "",
    taskStartDate: "",
    workflowInstanceDataFields:{
      Body: "",
      OccurrenceType: '',
      Category: '',
      LastOccurrence: new Date(),
      IsRecurring: false,
      ParticipantsList: [],
      Agenda: '',
      EndDate: '',
      Location: '',
      Subject: '',
      InstanceId: '',
      EventType: '',
      StartDate: '',
      MDEmail: '',
      MDName: '',
      IsAllDayEvent: false,
      Message: '',
      Status: ''
    }
  }

  show = false
  isRecurring:string;
  isEventEdited: boolean;
  profile:string;
  eventAttendees: EventPerson[];

  loadedEventAttachments: Attachment[];
  adding: "intervenient" | "CC" = "intervenient";

  showAttendees = false;

  InstanceId: string;

  Form: FormGroup;
  validateFrom = false

  @Output() openAttendeesComponent = new EventEmitter<any>();
  @Output() clearContact = new EventEmitter<any>();
  @Output() setIntervenient = new EventEmitter<any>();
  @Output() setIntervenientCC = new EventEmitter<any>();
  @Output() closeComponent = new EventEmitter<any>();
  @Output() closeEventToApprove = new EventEmitter<any>();

  @Input() saveData: any;
  @Input() serialNumber: string
  @Input() taskParticipants: EventPerson[];
  @Input() taskParticipantsCc: EventPerson[];

  constructor(
    private modalController: ModalController,
    private eventsService: EventsService,
    public alertController: AlertController,
    private attachmentsService: AttachmentsService,
    private processes:ProcessesService,
    private toastService: ToastService,
    public ThemeService: ThemeService
  ) {
    this.isEventEdited = false;
  }

  ngOnInit() {

    if(this.restoreTemporaryData()){
      this.setOtherData()
    } else {
      this.getTask();

    }
    this.getRecurrenceTypes();

  }

  async getTask() {

    this.processes.GetTask(this.serialNumber).subscribe( (result) =>{
      this.eventProcess = result

      this.eventProcess.workflowInstanceDataFields.LastOccurrence = new Date(this.eventProcess.workflowInstanceDataFields.LastOccurrence)

      this.restoreDatepickerData()

      // description
      let body : any =this.eventProcess.workflowInstanceDataFields.Body.replace(/<[^>]+>/g, '')
      this.eventProcess.workflowInstanceDataFields.Body = body
      this.eventProcess.workflowInstanceDataFields.Category = this.eventProcess.workflowInstanceDataFields.EventType

      this.InstanceId = this.eventProcess.workflowInstanceDataFields.InstanceId
      this.getAttachments()

      this.setOtherData()

      this.saveTemporaryData()
    })
  }

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

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

  setOtherData() {
    if(this.eventProcess.workflowInstanceDataFields.ParticipantsList) {
      this.eventProcess.workflowInstanceDataFields.ParticipantsList.forEach(e => {
        if(e.IsRequired) {
          this.taskParticipants.push(e);
        } else {
          this.taskParticipantsCc.push(e);
        }
      })
    }

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

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

    this.InstanceId = this.eventProcess.workflowInstanceDataFields.InstanceId

    this.getAttachments()
  }

  close() {

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

    // this.closeComponent.emit();

    this.closeEventToApprove.emit();
    
    this.setIntervenient.emit([]);
    this.setIntervenientCC.emit([]);
    this.clearContact.emit();

    //this.deleteTemporaryData();
  }


  runValidation() {
    this.validateFrom  = true
  }

  injectValidation() {

    this.Form = new FormGroup({
      Subject: new FormControl(this.eventProcess.workflowInstanceDataFields.Subject, [
        Validators.required,
        // Validators.minLength(4)
      ]),
      Location: new FormControl(this.eventProcess.workflowInstanceDataFields.Location, [
        Validators.required,
      ]),
      //CalendarName: new FormControl(this.postEvent.CalendarName),
      // Categories: new FormControl(this.postEvent.Categories, [
      //   Validators.required
      // ]),
      dateStart: new FormControl(this.dateStart, [
        Validators.required
      ]),
      dateEnd: new FormControl(this.dateEnd, [
        Validators.required
      ]),
      // IsRecurring: new FormControl(this.postEvent.IsRecurring, [
      //   Validators.required
      // ]),
      participantes: new FormControl(this.taskParticipants, [
        // Validators.required
      ]),

    })
  }

  async save() {

    this.injectValidation()
    this.runValidation()

    if(this.Form.invalid) return false

    // set dates to eventProcess object
    this.getDatepickerData()

    this.taskParticipantsCc.forEach( e => {
      e.IsRequired = false
    })

    this.eventProcess.workflowInstanceDataFields.ParticipantsList = this.taskParticipants.concat(this.taskParticipantsCc)

    this.eventProcess.workflowInstanceDataFields.ParticipantsList.forEach(e=>{

      if(e.hasOwnProperty('$type')) {
        delete e.$type
      }
    })

    const event: EventToApproveEdit = {
      SerialNumber: this.eventProcess.serialNumber,
      Body: this.eventProcess.workflowInstanceDataFields.Body,
      Location: this.eventProcess.workflowInstanceDataFields.Location,
      Subject: this.eventProcess.workflowInstanceDataFields.Subject,
      StartDate: this.eventProcess.workflowInstanceDataFields.StartDate,
      EndDate: this.eventProcess.workflowInstanceDataFields.EndDate,
      ReviewUserComment: '',
      Agenda: this.eventProcess.workflowInstanceDataFields.Agenda,
      MDName: this.eventProcess.workflowInstanceDataFields.MDName,
      MDEmail: this.eventProcess.workflowInstanceDataFields.MDEmail,
      IsAllDayEvent: this.eventProcess.workflowInstanceDataFields.IsAllDayEvent,
      Status: this.eventProcess.workflowInstanceDataFields.Status,
      EventType: this.eventProcess.workflowInstanceDataFields.EventType,
      IsRecurring: this.eventProcess.workflowInstanceDataFields.IsRecurring,
      Message: this.eventProcess.workflowInstanceDataFields.Message,
      EventRecurrence: {
        Type: this.eventProcess.workflowInstanceDataFields.OccurrenceType || '-1',
        LastOccurrence: this.eventProcess.workflowInstanceDataFields.LastOccurrence,
      },
      ParticipantsList: this.eventProcess.workflowInstanceDataFields.ParticipantsList,
      Category: this.eventProcess.workflowInstanceDataFields.Category
    }

    try {
      await  this.eventsService.postEventToApproveEdit(event).toPromise()
      
      this.close()

      this.toastService.successMessage('Evento editado');

    } catch(e) {
      this.toastService.badRequest('Evento não editado');
    }
  
    this.loadedAttachments.forEach((document:any)=>{
      if(document['action'] == 'add') {
        delete document.action
        this.attachmentsService.setEventAttachmentById(document).subscribe(()=>{
          // this.toastService.successMessage();
        }, error =>{
          this.toastService.badRequest();
        });
      } else if(document['action'] == 'delete') {
        delete document.action
        this.attachmentsService.deleteEventAttachmentById(document.Id).subscribe( res=>{
          // this.toastService.successMessage()
        }, error =>{
          this.toastService.badRequest()
        })
      }

    })

  }


  dynamicSetIntervenient({taskParticipants, taskParticipantsCc}) {
    this.taskParticipants = removeDuplicate(taskParticipants) ;
    this.taskParticipantsCc = removeDuplicate(taskParticipantsCc) ;
  }


  async addParticipants() {

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

    this.clearContact.emit();
  }


  async addParticipantsCC() {

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

    this.clearContact.emit();
  }

  saveTemporaryData() {

    this.getDatepickerData()

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


  restoreTemporaryData(): boolean {

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

    if(JSON.stringify(restoredData) != "{}" && undefined != restoredData) {
      this.eventProcess = restoredData.eventProcess

      // restore dater for date and hours picker
      this.restoreDatepickerData()
      return true;
    } else {

      return false;
    }
  }


  async getAttachments() {

   let result: any = await this.attachmentsService.getAttachmentsById(this.InstanceId).toPromise();

    result.forEach((e)=>{
      e.action = false
    })

    this.loadedAttachments = result

    // console.log('this.loadedAttachments', this.loadedAttachments, result)
  }

  deleteAttachment(attachment: Attachment, index) {

    this.loadedAttachments[index]['action'] = 'delete'
  }

  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: SearchList = res.data.selected;

        const DocumentToSave: any = {
          SourceTitle: data.Assunto,
          ParentId: this.InstanceId,
          Source: '1',
          SourceId: data.Id,
          ApplicationId: data.ApplicationType.toString(),
          Id: '',
          Link: '',
          SerialNumber: '',
          action: 'add',
          CreateDate: data.Data,
          Data: data.Data,
          Description: data.DocTypeDesc,
          SourceName: data.Assunto,
          Stakeholders: data.EntidadeOrganicaNome,
        };


        this.loadedAttachments.push(DocumentToSave)
        console.log('push', DocumentToSave)

        // await this.attachmentsService.setEventAttachmentById(DocumentToSave).subscribe(()=>{
        //   this.getAttachments();
        // });
      }
    });
  }

  restoreDatepickerData() {

    this.dateControlStart = new FormControl(moment(new Date(this.eventProcess.workflowInstanceDataFields.StartDate)));
    this.dateControlEnd = new FormControl(moment(new Date(this.eventProcess.workflowInstanceDataFields.EndDate)));

  }

  getDatepickerData() {

    this.eventProcess.workflowInstanceDataFields.StartDate = this.dateStart
    this.eventProcess.workflowInstanceDataFields.EndDate = this.dateEnd

  }

}
