import {AnalyticalScope, Behavior, LinkField, Visible} from "@webbpm/base-package";

@AnalyticalScope("LinkField")
export class GridSetRoleValuesScript extends Behavior {
  private linkField: LinkField;
  private userRemovedRoleIds: Set<any> = new Set();
  private initialized = false;

  initialize() {
    super.initialize();
    this.linkField = this.getScript(LinkField);
  }

  @Visible()
  public setValues(roleIdList: any[]) {
    if (!roleIdList || roleIdList.length === 0) {
      return;
    }

    if (!this.initialized) {
      this.linkField.setValue(roleIdList);
      this.initialized = true;
      return;
    }

    const existingRows = this.linkField.getAllRows();
    const existingRoleIds = new Set(existingRows.map(row => row.row_uid));
    roleIdList.forEach(id => {
      if (!existingRoleIds.has(id)) {
        this.userRemovedRoleIds.add(id);
      }
    });

    const toRemove = existingRows.filter(row =>
                                             !roleIdList.includes(row.row_uid) ||
                                             this.userRemovedRoleIds.has(row.row_uid)
    );
    const toAdd = roleIdList.filter(id =>
                                        !this.userRemovedRoleIds.has(id) &&
                                        !existingRoleIds.has(id)
    );

    const remainingIds = existingRows
        .filter(row => !toRemove.includes(row))
        .map(row => row.row_uid);

    const finalIds = [...remainingIds, ...toAdd];

    this.linkField.setValue(finalIds);
  }

  @Visible()
  public reset() {
    this.userRemovedRoleIds.clear();
    this.initialized = false;
  }
}