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

@AnalyticalScope("LinkField")
export class GridSetIpValuesScript extends Behavior {
  private linkField: LinkField;
  private userRemovedIps: Set<string> = new Set();
  private initialized = false;

  @NotNull()
  public columnName: string;

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

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

    if (!this.initialized) {
      this.addRows(ipList);
      this.initialized = true;
      return;
    }

    const existingRows = this.linkField.getAllRows();
    const existingIps = new Set(existingRows.map(row => row.row_uid));

    ipList.forEach(ip => {
      if (!existingIps.has(ip)) {
        this.userRemovedIps.add(ip);
      }
    });

    const toRemove = existingRows.filter(row =>
                                             !ipList.includes(row.row_uid) ||
                                             this.userRemovedIps.has(row.row_uid)
    );
    this.linkField.removeRows(toRemove);
    const toAdd = ipList
        .filter(ip =>
                    !this.userRemovedIps.has(ip) &&
                    !existingIps.has(ip)
        );
    this.addRows(toAdd);
  }

  private addRows(ips: any[]) {
    const rows = ips.map(ip => ({
      row_uid: ip,
      [this.columnName]: ip
    }));
    this.linkField.addRows(rows);
  }

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