import config from "./config/config";
import logging from "./config/logging";
import * as Xcron from "node-cron";
import { rpt_052_000 } from "./lib_052_master";

export const NAME_SPACE = "OneEtlTat Gateway";
const VERSION = "1.0";

let isRunning: boolean = false;
let isRefreshRunning: boolean = false;

logging.info(NAME_SPACE, "Starting " + VERSION);

const on_init = async () => {
  logging.info(NAME_SPACE, "On Init Start");
  await one_result_job();
  logging.info(NAME_SPACE, "On Init End");
};

on_init();

async function one_result_job() {
  if (isRunning) {
    logging.info(NAME_SPACE, "Still Running");
    return;
  }
  isRunning = true;
  try {
    const cur_date = new Date().toISOString().split("T")[0];

    // array kode
    const arrRpt = [
      { kode: "000", name: "from sp_rpt_052" },
      { kode: "001", name: "from sp_rpt_r_052i" },
      { kode: "002", name: "from sp_rpt_r_052ii" },
      { kode: "003", name: "from sp_rpt_r_052iii" },
      { kode: "004", name: "from sp_rpt_052iiii" },
      { kode: "005", name: "from sp_rpt_052iiiii" },
      { kode: "006", name: "from sp_rpt_052iiiiii" },
      { kode: "007", name: "from sp_rpt_052iiiiiii" },
      { kode: "008", name: "from sp_rpt_052iiiiiiii" },
      { kode: "009", name: "from sp_rpt_052iiiiiiiii" },
      // sekarang n
      { kode: "n006_unique", name: "from sp_rpt_r_052_Niiiiii" },
      { kode: "n007", name: "from sp_rpt_r_052_Niiiiiii" },
      { kode: "n008", name: "from sp_rpt_r_052_Niiiiiiii" },
      { kode: "n009", name: "from sp_rpt_r_052_Niiiiiiiii" },
      { kode: "online", name: "from sp_rpt_r_052_online" },
    ];

    const target = "0";

    logging.info(NAME_SPACE, "Starting Job " + VERSION);

    if (arrRpt.length > 0) {
      for (let index = 0; index < arrRpt.length; index++) {
        const element = arrRpt[index];
        // rpt_052_000
        logging.info(NAME_SPACE, "kode : " + element.kode);
        logging.info(NAME_SPACE, "nama rpt : " + element.name);
        var resp = await rpt_052_000(element.kode, cur_date, target);
        if (resp["status"] == "OK") {
          logging.info(NAME_SPACE, "\t Success");
        } else {
          logging.error(NAME_SPACE, "\t Error " + resp["message"]);
        }
        logging.info(NAME_SPACE, "Wait " + config.delay + " second");
        await delay(config.delay * 1000);
      }
    }

    logging.info(NAME_SPACE, "End Job");
    isRunning = false;
  } catch (e) {
    isRunning = false;
    if (e instanceof Error) {
      logging.error(NAME_SPACE, e.message);
    } else {
      logging.error(NAME_SPACE, "Unknown");
    }
  }
}
// console.log(config);
for (const sched of config.schedule) {
  Xcron.schedule(
    sched,
    async () => {
      await one_result_job();
    },
    {
      timezone: "Asia/Jakarta",
    }
  );
}

// ------------- function
async function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
