import { AfterViewChecked, ChangeDetectorRef, Component, OnInit, ViewContainerRef } from '@angular/core';
import { FormGroup, Validators, ValidationErrors, FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService, InitCommonsService, NotificationType } from '@xdf/commons';
import { IFormView, ColumnTemplate, GridTemplate, DynaDataService, AuditDialogService, ConfirmationDialogService, ValidatorUtils } from '@xdf/gallery';
import { NavigationService } from '@xdf/layouts';
import { Reservation } from '../../interfaces/reservation';
import { AgenteService } from '../../services/agente.service';
import { PasajeroService } from '../../services/pasajero.service';


@Component({
  selector: 'byte-reserva',
  templateUrl: './reserva.component.html',
  styleUrls: ['./reserva.component.scss']
})
export class ReservaComponent extends IFormView implements AfterViewChecked {

  columnTemplateArray: ColumnTemplate[];
  template: GridTemplate;
  title: string;
  sortColumn: any;
  sortDirection: any;
  listProxy = [];
  listPassenger = [];
  innerContent: any;
  disabledFields = [
    'id'
  ]
  type = [
    { name: "Primera Clase" }, { name: "Segunda Clase" }, { name: "Ejecutivo" }
  ]


  constructor(protected vcRef: ViewContainerRef,
    protected route: ActivatedRoute,
    protected router: Router,
    protected dynaDataService: DynaDataService,
    protected translate: TranslateService,
    protected notificationService: NotificationService,
    protected auditDialogService: AuditDialogService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected navigationService: NavigationService,
    protected init: InitCommonsService,
    protected validatorUtils: ValidatorUtils,
    protected proxyService: AgenteService,
    protected passengerService: PasajeroService,
    private readonly changeDetectorRef: ChangeDetectorRef) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);
  }

  ngAfterViewChecked(): void {
    this.changeDetectorRef.detectChanges();
  }

  protected getFields(): FormGroup {
    let form;
    if (this.mode !== 'new' && this.record) {
      form = new FormGroup({
        id: this.createFormControl('id', true, true),
        travelTypeClass: this.createFormControl('travelTypeClass', true, true),
        numberInParty: this.createFormControl('numberInParty', true, true, ''),
        proxyId: this.createFormControl('proxyId', true, true, ''),
        passengerId: this.createFormControl('passengerId', true, true, ''),
        //phoneNumber: this.createFormControl('phoneNumber', true, true, ''),
      });
    } else {
      form = new FormGroup({
        id: this.createFormControl('id', false, true),
        travelTypeClass: this.createFormControl('travelTypeClass', false, true),
        numberInParty: this.createFormControl('numberInParty', false, true, ''),
        proxyId: this.createFormControl('proxyId', false, true, ''),
        passengerId: this.createFormControl('passengerId', false, true, ''),
        //phoneNumber: this.createFormControl('phoneNumber', false, true, ''),
      });
    }
    return form;
  }

  ngOnInit() {
    super.ngOnInit();
    console.log(this.form);
    this.proxyService.getAllProxys().subscribe(res => {
      this.listProxy = res;
    });
    this.passengerService.getAllPassengers().subscribe(res => {
      this.listPassenger = res;
    });
  }

  completeForm() {
    this.record['id'] = this.id;
  }

  loadData(data) {
    this.record = data;
  }

  private createFormControl(name: string, existRecord?: boolean, required?: boolean, defaultValue?: string, validators?: Array<ValidationErrors>): FormControl {
    if (!defaultValue) defaultValue = '';
    let validatorList = [];
    if (validators) validatorList = validators;
    if (required) validatorList.push(Validators.required);
    let valueaux = existRecord ? this.record[name] : '';
    return new FormControl({ value: valueaux, disabled: this.disabledCondition(name) }, validatorList);
  }

  protected disabledCondition(controlName?): boolean {
    const disabled = this.mode === 'view' || this.disabledFields.includes(controlName);
    return disabled;
  }

  updateForm(id: any, mode: any) {
    this.mode = mode;
    this.id = id;
    if (this.id) {
      this.dynaDataService.getResult(this.id).subscribe(
        data => {
          this.record = data;
          this.form = this.getFields();
        }
      );
    } else {
      this.record = new Object();
      this.form = this.getFields();
    }
  }

  protected loadSettings() {
    this.title = this.templateDefinition.title;
    this.template = new GridTemplate(this.templateDefinition);
    this.innerContent = this.route.snapshot.data.innerTemplate;
    if (this.innerContent === 'none') {
      this.template.expandRow = false;
      this.innerContent = null;
    }
    if (this.template.expandRow && !this.innerContent) {
      const titleError = this.translate.instant('title.error');
      const error = this.translate.instant('inner.content.notfound.error');
      this.notificationService.showMessage(error, titleError, NotificationType.warning);
      this.template.expandRow = false;
    }
    this.sortColumn = this.template.sortColumnDefault;
    this.sortDirection = this.template.sortColumnDirection;
    this.columnTemplateArray = this.template.columnTemplateArray;
  }

  submit() {
    this.processing = true;
    if (this.mode === 'new') {
      let data = {};
      data['travelTypeClass'] = this.form.value['travelTypeClass'];
      data['numberInParty'] = this.form.value['numberInParty'];
      data['proxyId'] = this.form.value['proxyId'];
      data['passengerId'] = this.form.value['passengerId'];
      this.dynaDataService.create(data).subscribe(res => {
        const title = this.translate.instant('title.information');
        const message = this.translate.instant('message.create.succesful');
        this.notificationService.showMessage(
          message,
          title,
          NotificationType.success
        );
        this.record = new Object();
        this.router.navigate([this.returnUrl]);
        this.form.reset();
        this.processing = false;
      }, error => { this.processing = false });
    } else {
      this.record['travelTypeClass'] = this.form.value['travelTypeClass'];
      this.record['numberInParty'] = this.form.value['numberInParty'];
      this.record['proxyId'] = this.form.value['proxyId'];
      this.record['passengerId'] = this.form.value['passengerId'];
      this.dynaDataService.update(this.record['id'], this.record).subscribe(res => {
        const title = this.translate.instant('title.information');
        const message = this.translate.instant('message.update.succesful');
        this.notificationService.showMessage(
          message,
          title,
          NotificationType.success
        );
        this.form.markAsPristine();
        this.router.navigate([this.returnUrl]);
      });
    }
  }

}
