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';

@Component({
  selector: 'byte-agente',
  templateUrl: './agente.component.html',
  styleUrls: ['./agente.component.scss']
})
export class AgenteComponent 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),
        name: this.createFormControl('name', true, true),
        details: this.createFormControl('details', true, true, ''),
      });
    } else {
      form = new FormGroup({
        id: this.createFormControl('id', false, true),
        name: this.createFormControl('name', false, true),
        details: this.createFormControl('details', 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['name'] = this.form.value['name'];
      data['details'] = this.form.value['details'];
      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['name'] = this.form.value['name'];
      this.record['details'] = this.form.value['details'];
      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]);
      });
    }
  }
}
