import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { 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 { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';


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-new-action',
  templateUrl: './new-action.page.html',
  styleUrls: ['./new-action.page.scss'],
  providers: [
    { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
  ]
})
export class NewActionPage implements OnInit {

  folder: PublicationFolder;
  segment:string;

  Form: FormGroup;
  validateFrom = false

  public date: any;
  public disabled = false;
  public showSpinners = true;
  public showSeconds = false;
  public touchUi = false;
  public enableMeridian = false;
  public minDate = new Date().toISOString().slice(0,10)
  public endMinDate = new Date(new Date().getTime() + 15 * 60000);
  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;
  public dateControlStart = new FormControl(moment("DD MM YYYY hh"));
  public dateControlEnd = new FormControl(moment("DD MM YYYY hh"));

  showLoader = false

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

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

  constructor(
    private modalController: ModalController,
    private publication: PublicationsService,
    private toastService: ToastService

  ) {


    this.folder = new PublicationFolder();

    this.dateControlStart = new FormControl(moment(new Date()));
    this.dateControlEnd = new FormControl(moment(new Date(new Date().getTime() + 15 * 60000)));

    this.folder.DateBegin =  new Date().toISOString()
    this.folder.DateEnd = (new Date(new Date().getTime() + 15 * 60000)).toISOString()

  }

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

  setDefaultTime() {
    this.folder.DateBegin =  new Date().toISOString()
    this.folder.DateEnd = (new Date(new Date().getTime() + 15 * 60000)).toISOString()
  }

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

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

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

  injectValidation() {

    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

    this.folder = {
      ProcessId: null,
      Description: this.folder.Description,
      Detail: this.folder.Detail,
      DateBegin: this.folder.DateBegin,
      DateEnd: this.folder.DateEnd,
      ActionType: this.segment,
    }


    const loader = this.toastService.loading()

    try {
      await this.publication.CreatePublicationFolder(this.folder).toPromise();

      this.toastService.successMessage("Ação presidencial criado");
      this.close();
    } catch (error) {

      this.toastService.badRequest("Ação presidencial não criado");
    }     finally {
      loader.remove()
    }


  }

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

}
