

import { AfterViewChecked, ChangeDetectorRef, Component, EventEmitter, Output, ViewContainerRef } from '@angular/core';

import { ActivatedRoute, Router } from '@angular/router';
import { DynaDataService, AuditDialogService, ConfirmationDialogService, IFormView } from '@xdf/gallery';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService, InitCommonsService, NotificationType } from '@xdf/commons';
import { NavigationService } from '@xdf/layouts';
import { FormGroup, FormControl, Validators, ValidationErrors } from '@angular/forms';

import { GoalForActionService } from '../services/goalforaction.service';
import { AgentGoalService } from '../services/agent.service';
import { ActionService } from '../services/actions.service';

@Component({
  selector: 'byte-goal-form',
  templateUrl: './goal-form.component.html',
  styleUrls: ['./goal-form.component.scss']
})

export class GoalFormComponent extends IFormView implements AfterViewChecked {
  
  icon = '<i class=\"material-icons\">business_center</i>';
  disabledFields = ['id', 'identifier'];

  typeList:{value: number, label:string}[]=[];

  actionsList:{id: number, identifier:string}[]=[];

  goalActionList:{IdAction:number}[]=[];

  goalActionListloaded=false;
  actionLoaded=false;
  
  interForms = false;
  
  identifier:string
  agentId:string

  dirtytable=false;

  constructor(
    private readonly changeDetectorRef: ChangeDetectorRef,
    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 GoalForActionService: GoalForActionService,
    protected AgentGoalService: AgentGoalService,
    protected actionservice: ActionService
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);
  }

  changesDetected(){
    this.dirtytable=true;
  }

  isDirty(): boolean {
    return this.form.dirty || this.dirtytable;
  }

  ngOnInit(){
    super.ngOnInit();

    if(this.id){
      for(let i=0;i<this.record['actionList'].length;i++){
        this.goalActionList.push({
          IdAction: this.record['actionList'][i]['IdAction']
        });
      }
      this.actionservice.loadGoalActions(this.goalActionList);
      this.goalActionListloaded=true;
    }
    else{
      this.actionservice.loadGoalActions([]);
    }

    this.AgentGoalService.getAllAgent().subscribe(res=>{
      this.conversorAgenteList(res);
    });

    this.actionservice.getAllAction().subscribe(res=>{
      this.conversorActionList(res);
    });
    
  }

  getValueFromRecord(name: string) {
    let value = '';
    if (this.record && this.record[name]) {
      value = this.record[name];
    }
    return value;
  }

  protected getFields(): FormGroup {
    let form;
    if (this.mode !== 'new' && this.record) {
      form = new FormGroup({
        identifier: this.createFormControl('identifier', true, false),
        id: this.createFormControl('id', true, false),
        agentId: this.createFormControl('agentId',true,false),
      });
    } else {
      form = new FormGroup({
        id: this.createFormControl('id', false, false),
        identifier: this.createFormControl('identifier', false, false),
        agentId: this.createFormControl('agentId',false,false)
      });
    }
    return form;
  }

  conversorAgenteList(lista:any[]){
    for(let i=0;i<lista.length;i++){
      if(lista[i]['status']!="DE"){
        this.typeList.push({      
          value: lista[i]['id'],
          label: lista[i]['name']
        });
      }
    }
  }

  conversorActionList(lista:any[]){
    for(let i=0;i<lista.length;i++){
      this.actionsList.push({      
          id: lista[i]['id'],
          identifier: lista[i]['identifier']
      });
    }
    this.actionservice.loadActions(this.actionsList);
    this.actionLoaded=true;
  }

  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);
    }
    return new FormControl({ value: existRecord ? this.record[name] : '', disabled: this.disabledCondition() }, validatorList);
  }

  protected disabledCondition(): boolean {
    const disabled = this.mode === 'view';
    return disabled;
  }

  updateForm(id, mode) {
    this.mode = mode;
    this.id = id;
    this.form = this.getFields();
    if (this.id) {
      this.dynaDataService.getResult(this.id).subscribe(
        data => {
          this.record = data;
        }
      );
    }
  }

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

  submit() {
    this.dirtytable=false;
    this.interForms = false;
    super.submit();
  }

  completeForm(){
    this.record.agentId=this.form.controls['agentId'].value;
    this.record.identifier=this.form.controls['identifier'].value;
    this.record.actionList=this.actionservice.getGoalActions()
  }


}

