import Logs from "./logs.js";
import { getData, setData } from "./cache.js";
import { findCurrencyInfo } from "./globalData.js";

const accountOptionCacheFile = 'data/accountOptionCache.json';

const ACCOUNT_OPTIONS = {
  currentIndex: 0,
  nextChangeTime: 0,
};

const IS_DEV = process.env.NODE_ENV == 'development';

/**
 * 随机一个毫秒数
 * 范围：4小时 ~ 7小时
 * 测试环境范围：4分钟 ~ 7分钟
 * 加上当前时间戳
 * 计算下次切换时间
 */
const getRandomTime = () => {
  const nowTime = Date.now();
  const min = 1000 * 60 * (IS_DEV ? 1 : 60) * 4;
  const max = 1000 * 60 * (IS_DEV ? 1 : 60) * 7;
  const randomTime = Math.floor(Math.random() * (max - min + 1)) + min;
  return nowTime + randomTime;
}

/**
 * 缓存GLOBAL_DATA数据到文件
 * @returns {Promise<void>}
 */
const saveGlobalDataToCache = async () => {
  return setData(accountOptionCacheFile, ACCOUNT_OPTIONS);
}

/**
 * 从文件中加载GLOBAL_DATA数据
 * @returns {Promise<void>}
 */
const loadGlobalDataFromCache = async () => {
  return getData(accountOptionCacheFile)
  .then(data => {
    if (!data) {
      return;
    }
    Object.keys(ACCOUNT_OPTIONS)?.forEach(key => {
      if (key in data) {
        ACCOUNT_OPTIONS[key] = data[key];
      }
    });
  });
}

/**
 * 获取当前账号信息
 * @returns
 */
export const getAccountInfo = () => {
  const nowTime = Date.now();

  const accounts = process.env.PINNACLE_ACCOUNTS?.split(',').map(item => {
    const [username, password, localAddress, platform, currency='USD'] = item.split(':');
    return {
      username,
      password,
      localAddress,
      platform,
      currency,
      currencyInfo: findCurrencyInfo(currency),
    };
  }) ?? [];

  if (accounts.length == 0) {
    return null;
  }

  let isAccountChanged = false;

  if (ACCOUNT_OPTIONS.nextChangeTime == 0) {
    ACCOUNT_OPTIONS.currentIndex = 0;
    ACCOUNT_OPTIONS.nextChangeTime = getRandomTime();
  }
  else if (nowTime > ACCOUNT_OPTIONS.nextChangeTime) {
    ACCOUNT_OPTIONS.currentIndex++;
    if (ACCOUNT_OPTIONS.currentIndex >= accounts.length) {
      ACCOUNT_OPTIONS.currentIndex = 0;
    }
    ACCOUNT_OPTIONS.nextChangeTime = getRandomTime();
    isAccountChanged = true;
    saveGlobalDataToCache();
  }

  const accountInfo = accounts[ACCOUNT_OPTIONS.currentIndex];
  if (isAccountChanged) {
    const { password, ...accountInfoRest } = accountInfo;
    Logs.out('account changed', ACCOUNT_OPTIONS, accountInfoRest);
  }
  return accountInfo;
}

/**
 * 监听进程退出事件
 * 保存GLOBAL_DATA数据
 */
const saveExit = (code) => {
  saveGlobalDataToCache()
  .then(() => {
    Logs.out('account options saved');
  })
  .catch(err => {
    Logs.err('failed to save account options', err.message);
  })
  .finally(() => {
    process.exit(code);
  });
}
process.on('SIGINT', () => {
  saveExit(0);
});
process.on('SIGTERM', () => {
  saveExit(0);
});
process.on('SIGUSR2', () => {
  saveExit(0);
});

loadGlobalDataFromCache();
