import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { EventsService } from 'src/app/services/events.service';
import { Router } from '@angular/router';
import { Event } from '../../../models/event.model';
import { EventBody } from 'src/app/models/eventbody.model';
import { AlertController, ModalController } from '@ionic/angular';
import { EventPerson } from 'src/app/models/eventperson.model';
import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page';
import { AlertService } from 'src/app/services/alert.service';
import { Attachment } from 'src/app/models/attachment.model';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { AttachmentsPage } from '../attachments/attachments.page';


@Component({
  selector: 'app-event-detail',
  templateUrl: './event-detail.page.html',
  styleUrls: ['./event-detail.page.scss'],
})
export class EventDetailPage implements OnInit {

  loadedEvent: Event;
  loadedEventAttachments: Attachment[];
  pageId: string;
  showLoader: boolean;
  backURL: string;
  ionicForm: FormGroup;
  isSubmitted = false;

  minDate: Date;

  profile:string;


  constructor(
    public formBuilder: FormBuilder, 
    public alertController: AlertController, 
    private router: Router, 
    private activatedRoute: ActivatedRoute, 
    private eventsService: EventsService, 
    private modalCtrl: ModalController,
    private alertService: AlertService,
    private attachamentsService: AttachmentsService,
    private route: Router,
    private iab: InAppBrowser) { 
      this.loadedEvent = new Event();
      this.loadedEvent.Body = new EventBody();
    }

  ngOnInit() {
    this.loadEvent();
    this.loadAttachments();
    this.ionicForm = this.formBuilder.group({
      subject: ['', [Validators.required]]
    })
  }

  get errorControl() {
    return this.ionicForm.controls;
  }

  loadEvent(){
    let eventid: string;
    this.activatedRoute.paramMap.subscribe(paramMap =>
      {
        if (!paramMap.has("eventId")){
          return;
        }
        else{
          this.pageId = paramMap.get('eventId');
          eventid = paramMap.get('eventId');
          console.log(eventid);
          
        }
        if (paramMap.has("caller")){
          this.backURL = "/home/" + paramMap.get('caller');
        }
      }
    );
    this.eventsService.getEvent(eventid).subscribe(response => {
        this.loadedEvent = response;
      });
  }

  async openAttendees(){
    const modal = await this.modalCtrl.create({
      component: AttendeesPageModal,
       componentProps: {
        eventAttendees: this.loadedEvent.Attendees
      },
      cssClass: 'attendee modal-desktop',
      backdropDismiss: false
    });

    await modal.present();

    modal.onDidDismiss().then((data) => {
      if (data['data'] != null)
      { 
        let newattendees: EventPerson[] = data['data'];
        this.loadedEvent.Attendees = newattendees;
      }
    });
}

  getEventAttendees(): EventPerson[]
  {
    return this.loadedEvent.Attendees;
  }

  setEventAttendees(newattendes: EventPerson[])
  {
     this.loadedEvent.Attendees = newattendes;
  }

  async deleteConfirm()
  {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: 'Apagar evento!',
      message: 'Deseja <strong>apagar</strong> o evento da agenda ' + this.loadedEvent.CalendarName + '?',
      buttons: [
        {
          text: 'Não',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => { }
        }, {
          text: 'Sim',
          handler: () => {
            this.Delete();
          }
        }
      ]
    });

    await alert.present();
  }

  Delete()
  {
    this.eventsService.deleteEvent(this.loadedEvent.EventId, 0, this.loadedEvent.CalendarName).subscribe(async () => 
      {
        /* const alert = await this.alertController.create({
          cssClass: 'my-custom-class',
          header: 'Evento removido',
          buttons: ['OK']
        });
    
        await alert.present(); */

        this.router.navigate(['/home/events']);
      });  
  }

  Save()
  {
    if (this.ionicForm.valid){

      this.activatedRoute.paramMap.subscribe(paramMap =>{
        if (paramMap.has("profile")){
          console.log(paramMap.get('profile'));
          
        }
      });

     this.eventsService.editEvent(this.loadedEvent, 2, 3).subscribe(async () => 
      {
        const alert = await this.alertController.create({
          cssClass: 'my-custom-class',
          header: 'Evento actualizado',
          buttons: ['OK']
        });
  
        setTimeout(()=>{
        alert.dismiss();
      }, 1500);
      });
    }
  }

  showAlert(){
    this.alertService.presentAlert("Funcionalidade em desenvolvimento");
  }

  loadAttachments()
  { 
    /* console.log(this.pageId); */
    
    this.attachamentsService.getAttachmentsById(this.pageId).subscribe(res => {
      this.loadedEventAttachments = res;
      console.log(res);
      
    });
  }
  async viewDocument(documenturl:string)
  {
    const url: string = documenturl.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
    const browser = this.iab.create(url,"_blank");
    browser.show();
  }

  back()
  {
    //this.back();
  }
  doRefresh(event){
    /* this.RefreshEvents(); */
    event.target.complete();
     setTimeout(() => {
       event.target.complete();
     }, 2000);

  }
  navigateTo(ev){
    this.route.navigate(['/home/events',ev]);
  }
  async openAttachments(){
      const modal = await this.modalCtrl.create({
        component: AttachmentsPage,
         componentProps: {
           eventId: this.pageId,
          attachments: this.loadedEventAttachments
        },
        cssClass: 'attachments',
        backdropDismiss: false
      });
  
      await modal.present();
  
      modal.onDidDismiss().then((data) => {
        if (data['data'] != null)
        { 
          let newattendees: EventPerson[] = data['data'];
          this.loadedEvent.Attendees = newattendees;
        }
      });

  }
  
}
