import { AfterViewChecked, ChangeDetectorRef, Component, OnInit, 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 } from '@xdf/gallery';
import { NavigationService } from '@xdf/layouts';
import { param } from 'jquery';
import { element } from 'protractor';
import { PassengerService } from '../../service/passenger.service';

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

  disabledFields = [
    'id', 'name', 'lastname', 'phone', 'country', 'city', 'address', 'email'
  ];

  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,
    private activatedRouter: ActivatedRoute,
    private passengerService: PassengerService
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);
  }

  ngOnInit() {
    super.ngOnInit();
    this.serviceURL = "./service/passengers";
    this.icon = '<i class="fa fa-users fa-1_5x"></i>';
    this.id = parseInt(this.route.snapshot.queryParamMap.get('id'));
    this.dynaDataService.serviceURL = this.serviceURL;
    this.passengerService.serviceURL = this.serviceURL;
    this.updateForm(this.id, this.mode);
  }

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

  protected getFields(): FormGroup {
    let form;
    if (this.mode !== "new" && this.record) {
      form = new FormGroup({
        name: this.createFormControl("name", true, true),
        lastname: this.createFormControl("lastname", true, true),
        phone: this.createFormControl("phone", true, true),
        country: this.createFormControl("country", true, true),
        city: this.createFormControl("city", true, true),
        address: this.createFormControl("address", true, true),
        email: this.createFormControl("email", true, true),
        password: this.createFormControl("password", true, true),
      });
    } else {
      form = new FormGroup({
        name: this.createFormControl("name", false, true),
        lastname: this.createFormControl("lastname", false, true),
        phone: this.createFormControl("phone", false, true),
        country: this.createFormControl("country", false, true),
        city: this.createFormControl("city", false, true),
        address: this.createFormControl("address", false, true),
        email: this.createFormControl("email", false, true),
        password: this.createFormControl("password", false, true),
      });
    }
    return form;
  }

  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] : '';
    valueaux = this.mode === 'view' && name === 'password' ? '********' : valueaux;
    return new FormControl({ value: valueaux, disabled: this.disabledCondition(name) }, validatorList);
  }

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

  onSubmit() {
    this.processing = true;
    if (this.mode === 'new') {
      let data = this.form.value;
      this.passengerService.create(data).subscribe(response => {
        this.processing = false;
        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(['/agent/passengers']);
        this.form.reset();
        this.processing = false;
      }, error => {
        this.processing = false;
      });
    } else {
      let updatePassword = { password: this.form.value.password };
      this.passengerService.edit(updatePassword, this.id).subscribe(response => {
        this.processing = false;
        const title = this.translate.instant('title.information');
        const message = this.translate.instant('message.edit.succesful');
        this.notificationService.showMessage(message, title, NotificationType.success);
        this.record = new Object();
        this.router.navigate(['/agent/passengers']);
        this.form.reset();
        this.processing = false;
      });
    }
  }

  updateForm(id, mode) {
    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();
    }
  }

}
