const schedule = require("node-schedule");
// const executeWithRetry = require("./public/retry")
const Times = require("./public/times");
const HashRate = require("./src/hashrate");
const {Report, ReportEnx} = require("./src/report");
const Confirm = require("./src/confirm");
const Distribution = require("./src/distribution");
const { Balance, DGBBlance } = require("./src/blanace");
const Stats = require("./src/stat");
const ClearDBData = require("./src/clear")
const Notice = require("./src/notice");

const method = process.argv[2];
const methods = ["hashrate", "report", "clear", "distribution", "confirm", "balance", "stats", "notice"];

if (!methods.includes(method)) {
  throw `暂不支持${method}方法`;
}

const coin = process.argv[3];
const coins = ["nexa", "mona", "grs", "dgbq", "dgbs", "dgbo", "rxd", "enx", "alph"];
if (!coins.includes(coin)) {
  throw `暂不支持${coin}`;
}

if (method === "hashrate") {
  const hashrate = new HashRate(coin);
  schedule.scheduleJob({ minute: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55], second: [30] }, async () => {
    const ymd_now = Times.utcTime(Date.now().valueOf());
    const ymd = ymd_now.split(":");
    const end_time = ymd[0] + ":" + ymd[1] + ":" + "00";
    await hashrate.insert_hashrate_miners_table(end_time);
    const currentMinute = new Date().getMinutes();

    const data = await hashrate.query_hashrate_miners_accepts(end_time);
    if (currentMinute === 0 || currentMinute === 30) {
      await hashrate.insert_mhs(data);
      await hashrate.insert_mhs_real(data);
    } else {
      await hashrate.insert_mhs_real(data);
    }
  });
}

if (method === "report") {
  let report
  if(coin === "enx"){
    report = new ReportEnx(coin);
  } else {
    report = new Report(coin);
  }
  let interval = 60000;
  if (coin === "rxd") {
    interval = 300000;
  } else if (coin === "nexa") {
    interval = 120000;
  }
  setInterval(() => {
    report.main();
  }, interval);
}

// if (method === "confirm") {
//   // schedule.scheduleJob({hour:[1], minute:[30], second:[0]}, async () =>{
//   //   confirm.main();
//   // })
//   let interval = 600000;
//   if (coin === "rxd") {
//     interval = 1800000;
//   }
//   const confirm = new Confirm(coin);
//   setInterval(() => {
//     confirm.main();
//   }, interval);
// }


if (method === "confirm") {
  const confirm = new Confirm(coin);
  schedule.scheduleJob({hour:[1], minute:[30], second:[0]}, async () =>{
    confirm.main();
  })
}


if (method === "distribution") {
  const distribution = new Distribution(coin);
  schedule.scheduleJob({ hour: [0], minute: [1], second: [0] }, async () => {
    const now_ts = Date.now().valueOf();
    const last_ts = now_ts - 1000 * 60 * 60 * 24;
    const ymd_now = Times.utcTime(now_ts);
    const ymd_last = Times.utcTime(last_ts);
    const end_time = ymd_now.split(" ")[0] + " 00:00:00";
    const start_time = ymd_last.split(" ")[0] + " 00:00:00";
    await distribution.main(start_time, end_time);
  });
}

// if (method === "balance") {
//   const special_coins = ["dgbo", "dgbs", "dgbq"];
//   let balance;
//   if (special_coins.includes(coin)) {
//     balance = new DGBBlance(coin);
//   } else {
//     balance = new Balance(coin);
//   }
//   balance
//     .main()
//     .then(() => {
//       console.log("ok");
//     })
//     .catch((err) => {
//       console.log(err);
//     })
//     .finally(() => {
//       process.exit(0);
//     });
// }


if (method === "balance") {
  const special_coins = ["dgbo", "dgbs", "dgbq"];
  let balance;
  if (special_coins.includes(coin)) {
    balance = new DGBBlance(coin);
  } else {
    balance = new Balance(coin);
  }
  
  let hour = 4
  if(coin === "rxd" || coin === "alph"){
    hour = 9
  }
    
  async function task(balance) {
    let count = 0; // 让 count 成为 task 内部变量,避免多个 schedule 共享 count
    const last_height = await balance.node.getblockcount()
    while (count < 36) { // 最多执行 36 次 (6小时)
      const enable = await balance.query_now_height(last_height);
      if (enable) {
        await balance.main();
        console.log(`${coin}转账已完成`);
        return; // 成功执行后退出循环
      }
      console.log(`等待中... (已等待 ${count * 10} 分钟)`);
      await balance.sleep(1000 * 60 * 10); // 休眠 10 分钟
      count++;
    }
    console.log("等待超时,任务结束!");
  }  
  schedule.scheduleJob({hour: [hour], minute: [10], second: [0]}, async () => {
    await task(balance);
  });
}


if (method === "stats") {
  const stats = new Stats(coin);
  stats.caculate_user_should_distribution("2024-11-28 00:00:00");
}

if (method === "clear") {
  const clear = new ClearDBData(coin);
  clear
    .clearSharesDB(72)
    .then((res) => {
      console.log("sharesdb:ok");
    })
    .then(() => {
      clear.clearHashrateDB();
    })
    .then(() => {
      console.log("hashratedb:ok");
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      process.exit(0);
    });
  // clear.clearPoolDB("2024-10-11 00:00:00", "2024-12-23 00:00:00")
}

if (method === "notice") {
  const notice = new Notice(coin);
  schedule.scheduleJob({hour:[9], minute:[30], second:[0]}, () =>{
    notice.main()
  })
}