import { AfterViewChecked, ChangeDetectorRef, Component, OnInit, ViewContainerRef } from '@angular/core';
import { FormGroup, ValidationErrors, FormControl, Validators } 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';

@Component({
  selector: 'byte-aereopuerto',
  templateUrl: './aereopuerto.component.html',
  styleUrls: ['./aereopuerto.component.scss']
})
export class AereopuertoComponent 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),
        airportName: this.createFormControl('airportName', true, true),
        airportLocation: this.createFormControl('airportLocation', true, true),
        otherDetails: this.createFormControl('otherDetails', true, true, ''),
      });
    } else {
      form = new FormGroup({
        id: this.createFormControl('id', false, true),
        airportName: this.createFormControl('airportName', false, true),
        airportLocation: this.createFormControl('airportLocation', false, true),
        otherDetails: this.createFormControl('otherDetails', false, true, ''),
      });
    }
    return form;
  }

  ngOnInit() {
    super.ngOnInit();
  }

  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.form.value['id'] = 0;
    this.processing = true;
    if (this.mode === 'new') {
      let data = {};
      data['id'] = this.form.value['id'];
      data['airportName'] = this.form.value['airportName'];
      data['airportLocation'] = this.form.value['airportLocation'];
      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['airportName'] = this.form.value['airportName'];
      this.record['airportLocation'] = this.form.value['airportLocation'];
      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]);
      });
    }
  }
}
