import {
  checkArrayOfNumbers,
  checkNumber,
  funArrDiv,
  funArrMul,
  funArrSub,
  funMA,
  funRound,
  TMixed,
} from "../common";

export function EMV(
  HIGH: number[],
  LOW: number[],
  VOL: number[],
  N: number = 14,
  M: number = 9
): { EMV: TMixed[]; MAEMV: TMixed[] } {
  // check input
  checkArrayOfNumbers(HIGH, "HIGH");
  checkArrayOfNumbers(LOW, "LOW");
  checkArrayOfNumbers(VOL, "VOL");
  checkNumber(N, 2, HIGH, "N", "HIGH");
  checkNumber(M, 2, HIGH, "M", "HIGH");

  // calculate
  // VOLUME:=MA(VOL,N)/VOL;
  const VOLUME = funMA(VOL, N).map((item, index) =>
    item === null ? null : item / VOL[index]
  );

  // MID:=100*(HIGH+LOW-REF(HIGH+LOW,1))/(HIGH+LOW);
  const MID = [
    null,
    ...HIGH.slice(1).map(
      (item, index) =>
        ((item - HIGH[index] + LOW[index + 1] - LOW[index]) /
          (item + LOW[index + 1])) *
        100
    ),
  ];
  // EMV:MA(MID*VOLUME*(HIGH-LOW)/MA(HIGH-LOW,N),N);
  const EMV = funMA(
    funArrDiv(
      funArrMul(MID, funArrMul(VOLUME, funArrSub(HIGH, LOW))),
      funMA(funArrSub(HIGH, LOW), N)
    ),
    N
  );

  // MAEMV:MA(EMV,M);
  const MAEMV = funMA(EMV, M).map((v) => funRound(v, 3));
  return { EMV: EMV.map((v) => funRound(v, 3)), MAEMV };
}
