import config from "./config/config";
import logging from "./config/logging";
import * as Xcron from "node-cron";

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 {
    let dateTime = new Date();
    let dateTimeString = dateTime.toString();

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

    // rpt_052_000
    // logging.info(NAME_SPACE, "rpt_052_000");
    // var resp = await rpt_052_000("000",dateTimeString,"0");
    // 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));
}
