import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AnimationController, ModalController } from '@ionic/angular';
import * as moment from 'moment';
import { PublicationFolder } from 'src/app/models/publicationfolder';
import { PublicationsService } from 'src/app/services/publications.service';
import { ToastService } from 'src/app/services/toast.service';
import { BadRequestPage } from '../../popover/bad-request/bad-request.page';
import { SuccessMessagePage} from '../../popover/success-message/success-message.page';

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

  folder: PublicationFolder;
  segment:string;

  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 endMinDate = new Date(new Date().getTime() + 15 * 60000);

  Form: FormGroup;
  validateFrom = false

  public dateControlStart = new FormControl(moment("DD MM YYYY hh"));
  public dateControlEnd = new FormControl(moment("DD MM YYYY hh"));


  @Output() closeDesktopComponent= new EventEmitter<any>();
  @Output() getActions= new EventEmitter<any>();

  constructor(
    private publication: PublicationsService,
    private toastService: ToastService
  ) {
    this.folder = new PublicationFolder();


    this.folder = Object.assign(this.folder, {
      DateBegin: new Date().toISOString(),
      DateEnd: (new Date(new Date().getTime() + 15 * 60000)).toISOString(),
    })

  }

  get dateStart () {
    return this.dateControlStart.value
  }

  get dateEnd () {
    return this.dateControlEnd.value
  }

  ngOnInit() {
    this.segment = "Viagem";
  }

  segmentChanged(ev: any) {
    console.log(ev.detail.value);
  }

  get dateValid() {
    if (window.innerWidth >= 800) {
      return  new Date(this.folder.DateBegin).toLocaleString('pt')  <  new Date(this.folder.DateEnd).toLocaleString("pt")? ['ok'] : []
    } else {
      return ['ok']
    }
  }

  runValidation() {
    this.validateFrom  = true;
    if((new Date(this.folder.DateBegin).getTime()) > (new Date(this.folder.DateEnd).getTime())){
      this.toastService._badRequest("A data de início não pode ser superior a data de fim");
    }
    else if(new Date(this.folder.DateBegin).getTime() > new Date().getTime()){
      this.toastService._badRequest("A data de início não pode ser superior a data actual");
    }
  }

  injectValidation() {

    console.log(this.dateValid)

    this.Form = new FormGroup({
      Subject: new FormControl(this.folder.Description, [
        Validators.required,
        // Validators.minLength(4)
      ]),
      Date: new FormControl(this.dateValid, [
        Validators.required
      ]),
    })
  }


  async save() {

    this.injectValidation()
    this.runValidation()

    if(this.Form.invalid) {
      return false
    } else {
      console.log ('not passded')
    }

    console.log('pass')

    this.folder = {
      ProcessId: null,
      Description: this.folder.Description,
      Detail: this.folder.Detail,
      DateBegin: this.folder.DateBegin,
      DateEnd: this.folder.DateEnd,
      ActionType: this.segment,
    }
    console.log(this.folder);

    const loader = this.toastService.loading()

    try {
      await this.publication.CreatePublicationFolder(this.folder).toPromise()
      this.close();
      this.toastService._successMessage('Acção presidencial criada')

      this.getActions.emit()
    } catch (error) {
      this.toastService._badRequest('Não foi possivel criar a acção presidencial')
    }     finally {
      loader.remove()
    }

  }

  close(){
    this.closeDesktopComponent.emit();
  }

}
