import {
  aEqB,
  aGtB,
  aLtB,
  checkArrayOfNumbers,
  checkNumber,
  funMA,
  funMS,
  funRound,
  TMixed,
} from "../common";
export function VR(
  CLOSE: number[],
  VOL: number[],
  N: number = 26,
  M: number = 6
): { VR: TMixed[]; MAVR: TMixed[]; [key: string]: TMixed[] } {
  // check input
  checkArrayOfNumbers(CLOSE, "CLOSE");
  checkArrayOfNumbers(VOL, "VOL");
  checkNumber(N, 1, CLOSE, "N", "CLOSE");
  checkNumber(M, 1, CLOSE, "M", "CLOSE");

  // TH:=SUM(IF(CLOSE>REF(CLOSE,1),VOL,0),N);
  const TH: TMixed[] = funMS(
    [
      null,
      ...CLOSE.slice(1).map((v, i) => (aGtB(v, CLOSE[i]) ? VOL[i + 1] : 0)),
    ],
    N
  );

  // TL:=SUM(IF(CLOSE<REF(CLOSE,1),VOL,0),N);
  const TL: TMixed[] = funMS(
    [
      null,
      ...CLOSE.slice(1).map((v, i) => (aLtB(v, CLOSE[i]) ? VOL[i + 1] : 0)),
    ],
    N
  );

  // TQ:=SUM(IF(CLOSE=REF(CLOSE,1),VOL,0),N);
  const TQ: TMixed[] = funMS(
    [
      null,
      ...CLOSE.slice(1).map((v, i) => (aEqB(v, CLOSE[i]) ? VOL[i + 1] : 0)),
    ],
    N
  );

  // VR:100*(TH*2+TQ)/(TL*2+TQ);
  const VR: TMixed[] = TH.map((v, i) =>
    v === null || TL[i] === null || TQ[i] === null
      ? null
      : (100 * (v * 2 + TQ[i])) / (TL[i] * 2 + TQ[i])
  ).map((v) => funRound(v, 3));

  // MAVR:MA(VR,M);
  const MAVR: TMixed[] = funMA(VR, M).map((v) => funRound(v, 3));
  return { VR, MAVR };
}
