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 { ParticipantsPipe } from 'src/app/pipes/participants.pipe';
import { ThemeService } from 'src/app/services/theme.service'

@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 = [];
  selectedRecurringType: any;

  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>();

  showLoader = false

  @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' }
  ];

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

  private participantsPipe = new  ParticipantsPipe()

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

  ngOnInit() {

    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, '');
          }
        }
      }

      const result = this.participantsPipe.transform(this.postEvent.Attendees)
      this.taskParticipants = result.taskParticipants
      this.taskParticipantsCc = result.taskParticipantsCc

      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.initCalendarName = this.postEvent.CalendarName;

    this.loadedEventAttachments = this.loadedEventAttachments.concat(this.postEvent.Attachments)

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


  }

  ngOnChanges(changes: any): void {
    this.loadedEventAttachments = this.loadedEventAttachments.concat(this.postEvent.Attachments)
  }

  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
      ]),
      dateOccurrence: new FormControl(this.postEvent.EventRecurrence.Type, [
        Validators.required
      ]),
      participantes: new FormControl(this.taskParticipants, [
        // Validators.required
      ]),
      Date: new FormControl( new Date(this.postEvent.StartDate).toLocaleString('pt') < new Date(this.postEvent.EndDate).toLocaleString('pt')? '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.postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc);

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

    }

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

    this.showLoader = true;

    try {
      await this.eventsService.editEvent(this.postEvent, 2, 3).toPromise()
      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()
    } catch(error) {
      this.showLoader = false
      this.toastService.badRequest()
    }

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

    await this.saveDocument()

    this.close();
  }


  async saveDocument() {


    await this.loadedEventAttachments.forEach( async (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: '',
        };

        await this.attachmentsService.setEventAttachmentById(DocumentToSave).toPromise();
        await this.getAttachments(this.postEvent.EventId);

      } else if(remove) {
        await this.attachmentsService.deleteEventAttachmentById(e.Id).toPromise()
      }

    })

  }

  async addParticipants() {

    this.saveTemporaryData();

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

    this.clearContact.emit();
  }

  async addParticipantsCc() {

    this.saveTemporaryData();

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

    this.clearContact.emit();
  }


  saveTemporaryData() {

    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

      return true;
    } else {
      return false;
    }

  }

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

  async getAttachments(eventId: string){
    const rest: any = this.attachmentsService.getAttachmentsById(eventId).toPromise()
    this.loadedEventAttachments = rest;
  }

  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: data.selected.Stakeholders | data.selected.EntidadeOrganicaNome,
          ApplicationId: data.selected.ApplicationType.toString(),
          CreateDate: data.selected.Data,
          // needed to attach this document
          Id: 'add',
          SourceTitle: data.selected.Assunto,
          Source: '1',
          Link: '',
          SerialNumber: '',
        }

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

      }
    });
  }


}
