import { Component, OnInit } from '@angular/core';
import { AnimationController, ModalController, NavParams } from '@ionic/angular';
import { EventAttachment } from 'src/app/models/attachment.model';
import { EventBody } from 'src/app/models/eventbody.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { SearchList } from 'src/app/models/search-document';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { AuthService } from 'src/app/services/auth.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 { ThemePalette } from '@angular/material/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { EventRecurrence } from 'src/app/models/agenda/eventrecurrence.model';
import { ThemeService } from 'src/app/services/theme.service'


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

export class NewEventPage implements OnInit {
  // date picker
  public date: any;
  public disabled = false;
  public showSpinners = true;
  public showSeconds = false;
  public touchUi = false;
  public enableMeridian = false;
  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;
  public color: ThemePalette = 'primary';

  Form: FormGroup;
  validateFrom = false

  postEvent: Event;
  eventBody: EventBody;
  segment:string = "true";
  profile:string;
  eventAttendees: EventPerson[];
  selectedSegment: string;
  selectedDate: Date;
  recurringTypes: any;
  selectedRecurringType: any;

  adding: "intervenient" | "CC";

  taskParticipants: any = [];
  taskParticipantsCc: any = [];

  documents:SearchList[] = [];

  loggeduser: LoginUserRespose;
  members:any;
  CalendarName;

  constructor(
    private modalController: ModalController,
    private navParams: NavParams,
    private eventService: EventsService,
    private attachmentsService: AttachmentsService,
    private animationController: AnimationController,
    private toastService: ToastService,
    userService: AuthService,
    public ThemeService: ThemeService
  ) {
    this.loggeduser = userService.ValidatedUser;
    this.postEvent = new Event();
    this.postEvent.EventRecurrence = {Type:'-1'};
    this.eventBody = { BodyType : "1", Text : ""};
    this.postEvent.Body = this.eventBody;
    /* this.profile = this.navParams.get('profile'); */

    this.selectedSegment = this.navParams.get('segment');
    this.selectedDate = this.navParams.get('eventSelectedDate');
    this.taskParticipants = this.navParams.get('attendees');

    this.postEvent.StartDate =  new Date()
    this.postEvent.EndDate = (new Date(new Date().getTime() + 15 * 60000))
  }

  ngOnInit() {

    this.CalendarName = this.loggeduser.Profile;
    this.selectedRecurringType = "-1";
    console.log(this.postEvent);

    this.getRecurrenceTypes();

    /* console.log(this.profile); */

    let selectedStartdDate = this.selectedDate;
    let selectedEndDate = new Date(this.selectedDate);
    /* Set + 30minutes to seleted datetime */
    selectedEndDate.setMinutes(this.selectedDate.getMinutes() + 30) ;

    if(this.selectedSegment != "Combinada"){
      this.postEvent ={
        EventId: '',
        Subject: '',
        Body: this.eventBody,
        Location: '',
        CalendarId: '',
        CalendarName: '',
        StartDate: selectedStartdDate,
        EndDate: new Date(selectedEndDate),
        EventType: 'Reunião',
        Attendees: null,
        IsMeeting: false,
        IsRecurring: false,
        AppointmentState: 0,
        TimeZone: '',
        Organizer: '',
        Category: 'Reunião',
        HasAttachments: false,
        EventRecurrence: {Type:'-1'},
      };
    }
    else{
      this.postEvent ={
        EventId: '',
        Subject: '',
        Body: this.eventBody,
        Location: '',
        CalendarId: '',
        CalendarName: 'Oficial',
        StartDate: selectedStartdDate,
        EndDate: new Date(selectedEndDate),
        EventType: 'Reunião',
        Attendees: null,
        IsMeeting: false,
        IsRecurring: false,
        AppointmentState: 0,
        TimeZone: '',
        Organizer: '',
        Category: 'Reunião',
        HasAttachments: false,
        EventRecurrence: {Type:'-1'},
      };
    }

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

    console.log(this.postEvent);


  }

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


  getRecurrenceTypes() {
    this.eventService.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;
    if(new Date(this.postEvent.StartDate).getTime() > new Date(this.postEvent.EndDate).getTime()){
      this.toastService._badRequest("A data de fim não pode ser inferior a data de início do evento")
    }
  }


  get dateValid() {
    if (window.innerWidth <= 800) {
      return this.postEvent.StartDate < this.postEvent.EndDate? ['ok']: []
    } else {
      return ['ok']
    }
  }

  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
      ]),
      Date: new FormControl(this.dateValid, [
        Validators.required
      ]),
      Categories: new FormControl(this.postEvent.Category, [
        Validators.required
      ]),
      participantes: new FormControl(this.taskParticipants, [
        Validators.required
      ]),

    })
  }

  async save() {
    this.injectValidation()
    this.runValidation()

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

    if(this.documents.length >= 0) {
      this.postEvent.HasAttachments = true;
    }
    if(this.selectedRecurringType != '-1'){
      this.postEvent.EventRecurrence.Type = this.selectedRecurringType;
    }

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

   let eventId: any;

   const loader = this.toastService.loading()

    try {



      if(this.CalendarName == 'MDGPR') {
        console.log(this.loggeduser.Profile);

        console.log(this.postEvent);

        eventId = await this.eventService.postEventMd(this.postEvent, this.postEvent.CalendarName).toPromise();
        console.log(eventId);

      }
      else if(this.CalendarName == 'PR'){
        console.log(this.loggeduser.Profile);

        eventId = await this.eventService.postEventPr(this.postEvent, this.postEvent.CalendarName).toPromise();
      }

      const DocumentToSave: EventAttachment[] = this.documents.map((e) => {
        return {
          SourceTitle: e.Assunto,
          ParentId: eventId,
          Source: '1',
          SourceId: e.Id,
          ApplicationId: e.ApplicationType.toString(),
          Id: '',
          Link: '',
          SerialNumber: ''
        };
      });

      await  DocumentToSave.forEach( async (attachments, i) => {
        try {
          await this.attachmentsService.setEventAttachmentById(attachments).toPromise();
        } catch(error) {
          console.log('document not save')
        }

      });


      this.toastService._successMessage()
      this.modalController.dismiss(this.postEvent);


    } catch (error) {
      this.toastService._badRequest()
    } finally {
      loader.remove()
    }

  }

  async openAttendees() {

    const modal = await this.modalController.create({
      component: AttendeesPageModal,
       componentProps: {
        adding: this.adding,
        taskParticipants: this.taskParticipants,
        taskParticipantsCc: this.taskParticipantsCc
      },
      cssClass: 'attendee modal modal-desktop',
      backdropDismiss: false
    });

    await modal.present();

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

      if(data) {
        data = data['data'];
        if(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();
  }


  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((res)=>{
      if(res){
        const data = res.data;
        this.documents.push(data.selected);
      }
    });
  }

  removeAttachment(index: number){

    this.documents = this.documents.filter( (e, i) =>  index != i);

  }
}
