import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { ModalController, NavParams } from '@ionic/angular';
import { Event } from 'src/app/models/event.model'
import { EventPerson } from 'src/app/models/eventperson.model';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchDocumentDetails, SearchFolderDetails, SearchList } from 'src/app/models/search-document';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AuthService } from 'src/app/services/auth.service';
import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page';
import { ToastService } from 'src/app/services/toast.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import * as _moment from 'moment';
import * as _rollupMoment from 'moment';
import { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';
import { EventsService } from 'src/app/services/events.service';
import { EventService } from 'src/app/services/rules/event.service';
import { EventPipe } from 'src/app/pipes/event.pipe';
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-document-set-up-meeting',
  templateUrl: './document-set-up-meeting.page.html',
  styleUrls: ['./document-set-up-meeting.page.scss'],
  providers: [
    { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
  ]
})
export class DocumentSetUpMeetingPage implements OnInit {

  public date: any;
  public disabled = false;
  public showSpinners = true;
  public showSeconds = false;
  public touchUi = false;
  public enableMeridian = false;
  public minDate = new Date();

  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;

  p: any = {}

  Form: FormGroup;
  validateFrom = false
  recurringTypes = [];
  Occurrence: Date = new Date()
  EventRecurrenceType = '-1'
  showLoader = false

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

  taskParticipants: EventPerson[] = [];
  taskParticipantsCc: EventPerson[] = [];

  taskDocId:string;
  loadedAttachments:any;

  attachments: SearchList[] = [];

  adding: "intervenient" | "CC" = "intervenient";

  postData: Event;

  formLocationSatus: boolean = false;
  showAttendees= false;
  loggeduser: LoginUserRespose;
  emptyTextDescription = "Sem intervenientes selecionados";

  document: SearchFolderDetails | SearchDocumentDetails | any;
  subject: string;
  docs:any[] = [];

  eventPipe = new  EventPipe()

  constructor(
    private modalController: ModalController,
    private router:Router,
    private navParams: NavParams,
    authService: AuthService,
    private toastService: ToastService,
    private calendarService: EventsService,
    private eventService: EventService,
    public ThemeService: ThemeService
  ) {
    this.loggeduser = authService.ValidatedUser;
    this.document = this.navParams.get('document')
    this.subject = this.navParams.get('subject')

    this.postData = new Event();
    this.postData.Body ={ BodyType : "1", Text : ""};

    this.postData.Subject = this.subject
    this.postData.CalendarName = "Oficial";

    this.postData.Category = 'Reunião'
  }

  ngOnInit() {
    this.adding = "intervenient";
    this.setDefaultTime()
    this.getRecurrenceTypes();
  }

  getRecurrenceTypes() {
    this.calendarService.getRecurrenceTypes().subscribe( res=> {
      this.recurringTypes = res;
    });
  }

  setDefaultTime() {
    this.postData.StartDate =  new Date()
    this.postData.EndDate = (new Date(new Date().getTime() + 15 * 60000))
  }

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

  runValidation() {
    this.validateFrom  = true
  }

  injectValidation() {

    this.Form = new FormGroup({
      Subject: new FormControl(this.postData.Subject, [
        // Validators.required,
        // Validators.minLength(4)
      ]),
      Location: new FormControl(this.postData.Location, [
        // Validators.required,
      ]),
      CalendarName: new FormControl(this.postData.CalendarName, [
        // Validators.required
      ]),
      Date: new FormControl( (this.postData.StartDate < this.postData.EndDate), [
        Validators.required
      ]),
      participantes: new FormControl(this.taskParticipants, [
        // Validators.required
      ]),
      Categories: new FormControl(this.postData.Category, [
        // Validators.required
      ]),

    })
  }

  async saveTask() {

    if(this.loggeduser.Profile == 'MDGPR') {
      this.injectValidation()
      this.runValidation()
      if(this.Form.invalid) return false
    }

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

    if(this.document.Documents){
      this.document.Documents.forEach((e)=> {
        this.docs.push({
          ApplicationId: e.ApplicationId || e.ApplicationType,
          Source: 1,
          SourceId: e.DocId || e.docID || e.docId || e.SourceId,
          SourceName: e.Assunto
        })
      })
    }
    else{
      console.log(this.document);
      this.docs.push({
        ApplicationId: this.document.ApplicationId || this.document.ApplicationType,
        Source: 1,
        SourceId: this.document.DocId || this.document.docID || this.document.docId || this.document.SourceId,
        SourceName: this.document.Assunto
      })
    }

    let postEvent = {
      EventId: '',
      Subject: this.postData.Subject,
      Body: this.postData.Body.Text,
      Location: this.postData.Location,
      CalendarId: this.postData.CalendarName,
      CalendarName: this.postData.CalendarName,
      StartDate: this.postData.StartDate,
      EndDate: this.postData.EndDate,
      EventType: 'Reunião',
      Attendees: Attendees,
      IsMeeting: false, //
      IsRecurring: this.postData.IsRecurring,
      AppointmentState: 0, //
      TimeZone: '', //
      Organizer: '', //
      Category: 'Reunião',
      HasAttachments: false,
      EventRecurrence: {
        Type: this.EventRecurrenceType,
        LastOccurrence: this.Occurrence,
      },
      Attachments: this.docs,
    }

    const laoder = this.toastService.loading()

    this.eventService.create({ body: postEvent, calendar: this.postData.CalendarName }).subscribe(async (respose) => {
      laoder.remove()
      this.toastService._successMessage('Reunião criada')
      this.modalController.dismiss()
    }, (error) => {
      laoder.remove()
      this.toastService._badRequest('Não foi possível marcar a reunião');
    }, ()=>{
      laoder.remove()
    });

  }

  async addParticipants() {

    this.adding = "intervenient";

    if(window.innerWidth <= 801){
      const modal = await this.modalController.create({
        component: AttendeesPageModal,
          componentProps: {
          adding: this.adding,
          taskParticipants: this.taskParticipants,
          taskParticipantsCc: this.taskParticipantsCc
        },
        cssClass: 'modal 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'];

          this.setIntervenient(newAttendees);
          this.setIntervenientCC(newAttendeesCC);
        }
      });

    } else {
      this.showAttendees = true;
    }
  }

  async addParticipantsCc() {

    this.adding = "CC";

    if(window.innerWidth <= 800) {
      const modal = await this.modalController.create({
        component: AttendeesPageModal,
          componentProps: {
          adding: this.adding,
          taskParticipants: this.taskParticipants,
          taskParticipantsCc: this.taskParticipantsCc
        },
        cssClass: 'modal 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'];

          this.setIntervenient(newAttendees);
          this.setIntervenientCC(newAttendeesCC);
        }
      });
    } else {
      this.showAttendees = true;
    }
  }

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

  removeAttachment(index: number) {
    this.attachments = this.attachments.filter( (e, i) =>  index != i);
  }

  validateFormInputs(){
    let formLocation = this.postData.Location.trim();
    if(!this.postData.Location && formLocation.length <= 0){
      this.formLocationSatus = true;
    }
  }

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

  goToGabinete() {
    this.router.navigate(['/home/gabinete-digital']);
  }

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

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

}
