import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { Sid, Tip } from "./models/types";
import { Eno } from "./models/Eno";
import { IEnSrvOptions } from "./IEnSrvOptions";
import { pull, IPullOptions, pullSid } from "./pull";

export interface IReadOptions {
  branch?: string;
  ifNotSid?: string[];
  // watch?: boolean;
}

// Reads a single eno by tip
export function read(
  tip: Tip,
  enSrvOptions: IEnSrvOptions,
  readOptions?: IReadOptions
): Observable<Eno> {
  return pull([tip], enSrvOptions, readOptions as IPullOptions).pipe(
    map((responseBatch) => {
      for (let i = 0; i < responseBatch.length; i++) {
        if (responseBatch[i].tip === tip) {
          return responseBatch[i];
        }
      }
      throw new Error("error/message/eno/not-found");
    })
  );
}

// Reads a single eno by sid
export function readSid(
  sid: Sid,
  enSrvOptions: IEnSrvOptions,
  readOptions?: IReadOptions
): Observable<Eno> {
  return pullSid([sid], enSrvOptions, readOptions as IPullOptions).pipe(
    map((responseBatch) => {
      for (let i = 0; i < responseBatch.length; i++) {
        if (responseBatch[i].sid === sid) {
          return responseBatch[i];
        }
      }
      throw new Error("error/message/eno/not-found");
    })
  );
}
