import { EnumerationType } from './../../model/common-model';
import { ICellRendererParams } from "ag-grid-community";
import BaseRenderer from "./base-renderer";

export class ManyToManyTagRenderer extends BaseRenderer{
  public init(params: ICellRendererParams) {
    this.params = params;
    this.setupGui();
  }
  
  public setupContentGui(): string {
    if(this.params.data == null) {
      return '';
    }
    else {
      let allFieldPath: Array<string> = this.params.colDef.field.split('.');
      let arrayField = this.params.colDef.floatingFilterComponentParams.arrayField ?? this.params.colDef.field.split('.')[0];
      let arrayIndex = allFieldPath.findIndex(x => x == arrayField);
      let fieldPath: Array<string> = allFieldPath.slice(arrayIndex + 1);
      let arrayName: Array<string> = allFieldPath.slice(0, arrayIndex + 1);
      let array: any = this.params.data;
      arrayName.forEach(x => {
        if (array != null) {
          array = array[x];
        }
      });
      if(array == null){
        return "";
      }

      return (array as Array<EnumerationType>).map((element: any) => {
        let fieldValue: any = element;
        let enumerationType: EnumerationType;
        for (let fieldName of fieldPath) {
          if(fieldName == "denomination") {
            enumerationType = fieldValue;
          }
          if (fieldValue == null) return '';
          fieldValue = fieldValue[fieldName];
        }
        return `<ui-tag label="${fieldValue as string}" text-color="${enumerationType?.textColor}" background-color="${enumerationType?.backgroundColor}" size="md" type="solid"></ui-tag>`
      }).join('');
    }   
  }
}
