const axios = require('axios');

const apiUrl = 'https://webapi.sporttery.cn/gateway/uniform/football/getMatchCalculatorV1.qry?poolCode=hhad,had&channel=c';

const ratioAccept = (ratio) => {
  if (ratio > 0) {
    return 'a'
  }
  return ''
}

const ratioString = (ratio) => {
  ratio = Math.abs(ratio);
  ratio = ratio.toString();
  ratio = ratio.replace(/\./, '');
  return ratio;
}

const parseEvents = (oddsInfo) => {
  const { h, d, a, goalLineValue, poolId } = oddsInfo;
  const gv = +goalLineValue;
  const events = {};
  const special = {};
  const ratio_rh = gv - 0.5;
  const ratio_rc = -(gv + 0.5);

  if (!gv) {
    events['ior_mn'] = +d;
  }
  else {
    special[`ior_wm${gv > 0 ? 'c' : 'h'}_${Math.abs(gv)}`] = +d;
  }

  events[`ior_r${ratioAccept(ratio_rh)}h_${ratioString(ratio_rh)}`] = +h;
  events[`ior_r${ratioAccept(ratio_rc)}c_${ratioString(ratio_rc)}`] = +a;

  return { events, special };
}

const getGamesEvents = async () => {
  return axios.get(apiUrl, {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36'
    },
    proxy: false,
  })
  .then(res => res.data)
  .then(ret => {
    const { success, value } = ret;
    if (!success || !value) {
      return;
    }
    const { matchInfoList } = value;
    const matchList = matchInfoList?.map(item => {
      const { subMatchList } = item;
      return subMatchList.map(match => {
        const { leagueAllName, leagueId,
          homeTeamAllName, awayTeamAllName,
          matchDate, matchTime,
          oddsList, matchId } = match;
        const timestamp = new Date(`${matchDate} ${matchTime}`).getTime();

        const oddsValues = { events: {}, special: {} };
        oddsList.map(parseEvents).forEach(odds => {
          oddsValues.events = { ...oddsValues.events, ...odds.events };
          oddsValues.special = { ...oddsValues.special, ...odds.special };
        });

        const evtime = Date.now();
        const sptime = Date.now();

        return {
          leagueId,
          eventId: matchId,
          leagueName: leagueAllName,
          teamHomeName: homeTeamAllName,
          teamAwayName: awayTeamAllName,
          timestamp,
          ...oddsValues,
          evtime,
          sptime,
        }
      });
    });
    return matchList?.flat() ?? [];
  })
}

const updateGamesList = ({ platform, games }) => {
  axios.post('http://127.0.0.1:9055/api/triangle/update_games_list', { platform, games })
  .then(res => res.data)
  .then(ret => {
    if (ret.code) {
      throw new Error(ret.message);
    }
  })
  .catch(error => {
    console.log('%cupdate game list failed, %s', 'color:#c00', error.message, platform);
  });
}

setInterval(() => {
  getGamesEvents()
  .then(gamesEvents => {
    updateGamesList({ platform: 'jc', games: gamesEvents });
    // console.log(JSON.stringify(gamesEvents, null, 2));
    // console.log(new Date());
  })
  .catch(err => {
    console.error(err);
  });
}, 5000);