import Logs from '../libs/logs.js';
import { getPassableEvents, eventsCombination } from './trangleCalc.js';
import { getSetting, updateSetting } from './settings.js';

const Request = {
  callbacks: {},
  count: 0,
}

const GLOBAL_DATA = {
  relationLength: 0,
  loopStatus: -1,
};

const getDataFromParent = (type, callback) => {
  const id = ++Request.count;
  Request.callbacks[id] = callback;
  process.send({ method: 'get', id, type });
}

const postDataToParent = (type, data) => {
  process.send({ method: 'post', type, data });
}

process.on('message', (message) => {
  const { callbacks } = Request;
  const { method, id, type, data } = message;
  if (method == 'get' && id) {
    let responseData = null;
    // if (data == 'getSolution') {
    //   responseData = Solution.get();
    // }
    process.send({ type: 'response', id, data: responseData });
  }
  else if (method == 'post') {
    if (type == 'updateSetting') {
      updateSetting(data);
    }
  }
  else if (type == 'response' && id && callbacks[id]) {
    callbacks[id](data);
    delete callbacks[id];
  }
});

/**
 * 精确浮点数字
 * @param {number} number
 * @param {number} x
 * @returns {number}
 */
const fixFloat = (number, x=2) => {
  return parseFloat(number.toFixed(x));
}

const getGamesRelation = () => {
  const setting = getSetting();
  const status = +setting.runWorkerEnabled;
  if (GLOBAL_DATA.loopStatus !== status) {
    GLOBAL_DATA.loopStatus = status;
    Logs.out('loop status changed to', status);
  }

  if (!setting.runWorkerEnabled) {
    return Promise.resolve([]);
  }
  return new Promise(resolve => {
    getDataFromParent('getGamesRelation', (relations) => {
      resolve(relations);
    });
  });
}

const updateSolutions = (solutions, eventsLogsMap) => {
  postDataToParent('updateSolutions', { solutions, eventsLogsMap });
}

const eventMatch = () => {
  getGamesRelation()
  .then(relations => {

    const relationLength = relations?.length;
    if (!relationLength) {
      if (GLOBAL_DATA.relationLength) {
        GLOBAL_DATA.relationLength = 0;
        Logs.out('relation list is empty');
      }
      return [];
    }

    GLOBAL_DATA.relationLength = relationLength;

    /** 日志 盘口信息 */
    const eventsLogsMap = {
      expireEvents: [],
      removeEvents: []
    };
    /** 日志 End */

    const passableEvents = getPassableEvents(relations, eventsLogsMap);
    const solutions = eventsCombination(passableEvents);

    // Logs.out('eventMatch solutions', solutions);
    if (solutions?.length) {
      updateSolutions(solutions, eventsLogsMap);
    }
  })
  .finally(() => {
    setTimeout(() => {
      eventMatch();
    }, 2000);
  });
};

const syncSetting = () => {
  getDataFromParent('getSetting', (setting) => {
    if (setting) {
      updateSetting(setting);
    }
    else {
      Logs.out('syncSetting setting is empty');
    }
  });
}

syncSetting();
eventMatch();
