import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { Batch, Sid, Tip } from "./models/types";
import { EnoFactory } from "./EnoFactory";
import { IEnSrvOptions } from "./IEnSrvOptions";
import { send } from "./send";
import { checkBatchForError, ERROR_MESSAGE_TIP } from "./error";

export interface IPullOptions {
  branch?: string;
  recursiveField?: string[];
  recursiveDepth?: number;
  ifNotSid?: string[];
  // watch?: boolean;
  skipErrors?: ERROR_MESSAGE_TIP[];
}

export function pull(
  tips: Tip[],
  enSrvOptions: IEnSrvOptions,
  pullOptions?: IPullOptions
): Observable<Batch> {
  if (!pullOptions) {
    pullOptions = {};
  }
  const batch: Batch = [];
  const branch = pullOptions.branch || "branch/master";
  const enoFactory = new EnoFactory("op/pull", "security/policy/op");
  enoFactory.setField("op/pull/tip", tips);
  enoFactory.setField("op/pull/branch", [branch]);
  if (pullOptions.ifNotSid) {
    enoFactory.setField("op/pull/if-not-sid", pullOptions.ifNotSid);
  }
  if (pullOptions.recursiveField) {
    enoFactory.setField("op/pull/recursive-field", pullOptions.recursiveField);
  }
  if (pullOptions.recursiveDepth) {
    enoFactory.setField("op/pull/recursive-depth", [
      "" + pullOptions.recursiveDepth,
    ]);
  }
  // if (pullOptions.watch) {
  //     enoFactory.setField('op/pull/watch', ['true']);
  // }

  const pullOp = enoFactory.makeEno();
  batch.push(pullOp);

  return send(batch, enSrvOptions).pipe(
    map((batchReturned) =>
      checkBatchForError(batchReturned, pullOptions.skipErrors)
    )
  );
}

export function pullSid(
  sids: Sid[],
  enSrvOptions: IEnSrvOptions,
  pullOptions?: IPullOptions
): Observable<Batch> {
  if (!pullOptions) {
    pullOptions = {};
  }
  const batch: Batch = [];
  const enoFactory = new EnoFactory("op/pull", "security/policy/op");
  enoFactory.setField("op/pull/sid", sids);
  if (pullOptions.recursiveField) {
    enoFactory.setField("op/pull/recursive-field", pullOptions.recursiveField);
  }
  if (pullOptions.recursiveDepth) {
    enoFactory.setField("op/pull/recursive-depth", [
      "" + pullOptions.recursiveDepth,
    ]);
  }

  const pullOp = enoFactory.makeEno();
  batch.push(pullOp);

  return send(batch, enSrvOptions).pipe(
    map((batchReturned) =>
      checkBatchForError(batchReturned, pullOptions.skipErrors)
    )
  );
}
