import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AlertController, AnimationController, ModalController, NavParams } from '@ionic/angular';
import { Attachment } from 'src/app/models/attachment.model';
import { EventBody } from 'src/app/models/eventbody.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { EventsService } from 'src/app/services/events.service';
import { ToastService } from 'src/app/services/toast.service';
import { Event } from '../../../models/event.model';
import { AttendeesPageModal } from '../../events/attendees/attendees.page';
import { SearchPage } from '../../search/search.page';
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 {

  Form: FormGroup;
  validateFrom = false
  public endMinDate = new Date(new Date().getTime() + 15 * 60000);
  public minDate = new Date().toISOString().slice(0,10)

  postEvent: Event;
  isRecurring:string;
  isEventEdited: boolean;
  loadedEvent: Event;
  eventBody: EventBody;
  segment:string = "true";
  profile:string;
  eventAttendees: EventPerson[];
  selectedSegment: string;
  selectedDate: Date;
  initCalendarName: string;
  caller:string;
  recurringTypes: any;
  selectedRecurringType: any;

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

  showAttendees = false;

  constructor(
    private modalController: ModalController,
    private navParams: NavParams,
    private eventsService: EventsService,
    public alertController: AlertController,
    private attachmentsService: AttachmentsService,
    private toastService: ToastService,
    private router: Router,
    public ThemeService: ThemeService
  ) {

    this.postEvent = new Event();
    this.isEventEdited = false;
    this.postEvent.EventRecurrence = { Type:'-1', LastOccurrence:''};
    this.postEvent = this.navParams.get('event');
    this.caller = this.navParams.get('caller');
    this.initCalendarName = this.postEvent.CalendarName;

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

    if(this.postEvent.Attendees == null) {
      this.taskParticipants = []
    } else {

      this.postEvent.Attendees.forEach(e =>{
        if(e.IsRequired){
          this.taskParticipants.push(e);
        } else {
          this.taskParticipantsCc.push(e);
        }
      })
    }

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

    this.getAttachments(this.postEvent.EventId);

  }

  ngOnInit() {
    window.onresize = (event) => {
      // if not mobile remove all component
      if( window.innerWidth >= 1024) {
        this.modalController.dismiss();
      }
    }
    if(window.innerWidth > 800){
      this.showAttendees=true;
    }

    this.getRecurrenceTypes();
    setTimeout(() => {
      this.selectedRecurringType = this.postEvent.EventRecurrence.Type.toString();
    }, 500);

  }

  close() {
    this.modalController.dismiss();
  }

  goBack() {
    console.log(this.caller);
    this.router.navigate(['/home',this.caller]);
  }

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

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


  runValidation() {
    this.validateFrom  = true
  }

  injectValidation() {

    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, [
        Validators.required
      ]),
      Categories: new FormControl(this.postEvent.Category, [
        Validators.required
      ]),
      IsRecurring: new FormControl(this.postEvent.IsRecurring, [
        Validators.required
      ]),
      Date: new FormControl(new Date(this.postEvent.StartDate).getTime() < new Date(this.postEvent.EndDate).getTime()? 'ok': null,[
        Validators.required
      ]),

      participantes: new FormControl(this.taskParticipants, [
      Validators.required
      ]),

    })
  }


  save() {

    this.injectValidation()
    this.runValidation()

    if(this.Form.invalid) return false;
    if(this.selectedRecurringType != '-1'){
      this.postEvent.EventRecurrence.Type = this.selectedRecurringType;
    }

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

    this.postEvent.EventRecurrence.Type = this.selectedRecurringType;

    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 (error) {}
        finally {
          this.goBack();
        }
  
      }

      this.toastService.successMessage();

    }, error => {
      if(error.status != 0)
      this.toastService.badRequest()
    });

    this.isEventEdited = true;

    this.modalController.dismiss(this.isEventEdited);


    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 openAttendees() {
    if(window.innerWidth > 801){
      this.showAttendees=true;
    }
    else{
      const modal = await this.modalController.create({
        component: AttendeesPageModal,
          componentProps: {
          adding: this.adding,
          taskParticipants: this.taskParticipants,
          taskParticipantsCc: this.taskParticipantsCc
        },
        cssClass: 'modal attendee modal-desktop',
        backdropDismiss: false
      });

      await modal.present();

      modal.onDidDismiss().then((data) => {

        if(data){
          data = data['data'];

          const newAttendees: EventPerson[] = data['taskParticipants'];
          const newAttendeesCC: EventPerson[] = data['taskParticipantsCc'];

          if(newAttendees.length) {
            this.setIntervenient(newAttendees);
          }
          if(newAttendeesCC) {
            this.setIntervenientCC(newAttendeesCC);
          }

        }
      });
    }


  }

  setIntervenient(data){
    this.taskParticipants = data;
    this.postEvent.Attendees = data;
  }

  setIntervenientCC(data){
    this.taskParticipantsCc = data;
  }

  addParticipants(){
    this.adding = 'intervenient'
    this.openAttendees();
  }

  addParticipantsCC(){
    this.adding = 'CC';
    this.openAttendees();
  }

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


  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)

      }
    })
  }

}
