import { DEBUG, enablePromise } from 'react-native-sqlite-storage';
import getDb from './moneyDB'

DEBUG(true);
enablePromise(true);

const outMoney = async ({ year, month }) => {
  const thisFirst = new Date(year, month, 1); //이번 달의 첫째 날
  const thisLast = new Date(year, month + 1, 0); //이번 달의 마지막 날

  const db = await getDb();
  return new Promise((res, rej) => {
    db.transaction(async (tx) => {
      console.log('차트 페이지');
      const [txn, results] = await tx.executeSql(`SELECT category_id, sum(price) as total from (SELECT type, price, category from money where date BETWEEN "${String(thisFirst.toJSON()).split(/T/)[0]}" and "${String(thisLast.toJSON()).split(/T/)[0]}") WHERE type='지출' group by category`);
      const temp = [];
      let totalP = 0;
      for (let i = 0; i < results.rows.length; i++) {
        console.log('chart', results.rows.item(i))
        if (results.rows.item(i).category === 1) {
          temp.push({
            name: "식비", total: results.rows.item(i).total, color: "#b0c4de", legendFontColor: "#7F7F7F",
            legendFontSize: 15
          })
        } else if (results.rows.item(i).category === 2) {
          temp.push({
            name: "교통비", total: results.rows.item(i).total, color: "#ffa07a", legendFontColor: "#7F7F7F",
            legendFontSize: 15
          })
        } else if (results.rows.item(i).category === 3) {
          temp.push({
            name: "문화비", total: results.rows.item(i).total, color: "rgba(131, 167, 234, 1)", legendFontColor: "#7F7F7F",
            legendFontSize: 15
          })
        }
      }
      console.log('chart temp', temp)
      res(temp)
    })
  })
}

const chartApi = {
  outMoney
}

export default chartApi;