import { AfterViewChecked, AfterViewInit, 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 { AgentService } from '../../service/agent.service';

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

  disabledFields = [
    'id', 'name', 'lastname', 'email', 'details'
  ];

  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 agentService: AgentService
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);
  }

  ngOnInit() {
    super.ngOnInit();
    this.serviceURL = "./service/agents";
    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.agentService.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),
        details: this.createFormControl("details", 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),
        details: this.createFormControl("details", 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.agentService.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(['/supervisor/agents']);
        this.form.reset();
        this.processing = false;
      }, error => {
        this.processing = false;
      });
    } else {
      let updatePassword = { password: this.form.value.password };
      this.agentService.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(['/supervisor/agents']);
        this.form.reset();
        this.processing = false;
      });
    }
  }

}
