import { AfterViewChecked, ChangeDetectorRef, Component, ViewContainerRef } from '@angular/core';
import { FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { InitCommonsService, NotificationService, NotificationType } from '@xdf/commons';
import { AuditDialogService, ConfirmationDialogService, DynaDataService, IFormView, ValidatorUtils, ColumnTemplate, GridTemplate } from '@xdf/gallery';
import { NavigationService } from '@xdf/layouts';
import { data } from 'jquery';

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

  columnTemplateArray: ColumnTemplate[];
  template: GridTemplate;
  title: string;
  sortColumn: any;
  sortDirection: any;
  innerContent: any;
  disabledFields = [
    'id'
  ]

  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,
    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),
        firstName: this.createFormControl('firstName', true, true),
        secondName: this.createFormControl('secondName', true, true, ''),
        lastName: this.createFormControl('lastName', true, true, ''),
        phoneNumber: this.createFormControl('phoneNumber', true, true, ''),
        emailAddress: this.createFormControl('emailAddress', true, true, ''),
        city: this.createFormControl('city', true, true, ''),
        otherDetails: this.createFormControl('otherDetails', true, true, '')
      });
    } else {
      form = new FormGroup({
        id: this.createFormControl('id', false, true),
        firstName: this.createFormControl('firstName', false, true),
        secondName: this.createFormControl('secondName', false, true, ''),
        lastName: this.createFormControl('lastName', false, true, ''),
        phoneNumber: this.createFormControl('phoneNumber', false, true, ''),
        emailAddress: this.createFormControl('emailAddress', false, true, ''),
        city: this.createFormControl('city', false, true, ''),
        otherDetails: this.createFormControl('otherDetails', false, true, '')
      });
    }
    return form;
  }
  
  ngOnInit() {
    super.ngOnInit();
    if (this.form) {
      console.log(this.form)
      this.form.controls['phoneNumber'].setValidators([Validators.pattern("^[0-9]{9}$")]);
      this.form.controls['emailAddress'].setValidators([Validators.required,Validators.email]);
    }
  }

  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['firstName'] = this.form.value['firstName'];
      data['secondName'] = this.form.value['secondName'];
      data['lastName'] = this.form.value['lastName'];
      data['phoneNumber'] = this.form.value['phoneNumber'];
      data['emailAddress'] = this.form.value['emailAddress'];
      data['city'] = this.form.value['city'];
      data['otherDetails'] = this.form.value['otherDetails'];
      console.log(data);
      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['firstName'] = this.form.value['firstName'];
      this.record['secondName'] = this.form.value['secondName'];
      this.record['lastName'] = this.form.value['lastName'];
      this.record['phoneNumber'] = this.form.value['phoneNumber'];
      this.record['emailAddress'] = this.form.value['emailAddress'];
      this.record['city'] = this.form.value['city'];
      this.record['otherDetails'] = this.form.value['otherDetails'];
      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]);
      });
    }
  }

}
