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

DEBUG(true);
enablePromise(true);

const colorArr = [
  "#f06c77", "#ffa07a", "#fafad2", "#e3fad2", "#b0c4de",
  "#49618f", "#dda0dd", "#ff4d6a", "#fcc24c", "#fffacd",
  "#8fbc8f", "#82a6e9", "#2b4069", "#db7093", "#fa8072",
  "#98fb98", "#d6badb"
]

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) => {
      const [txn, results] = await tx.executeSql(`SELECT category_id, category_name, sum(price) as total from (SELECT money.type_id, price, money.category_id, category_name FROM money inner JOIN categories on money.category_id = categories.category_id where date BETWEEN "${getDateStr(thisFirst)}" and "${getDateStr(thisLast)}") WHERE type_id=2 group by category_id`);
      const temp = [];
      for (let i = 0; i < results.rows.length; i++) {
        temp.push({
          name: results.rows.item(i).category_name,
          total: results.rows.item(i).total,
          color: colorArr[i], legendFontColor: "#7F7F7F",
          legendFontSize: 15
        })
      }
      res(temp)
    })
  })
}

const yearMoney = async ({ year }) => {
  const db = await getDb();  

  return new Promise((res, rej) => {
    db.transaction(async (tx) => {
      const [txn, results] = await tx.executeSql(`SELECT strftime('%m',date) as month, type_id, sum(price) as total from money where strftime('%Y', date)= "${year}" GROUP by strftime('%m', date), type_id `);
      const temp1 = [];
      const temp2 = [];
      let temparr1 = new Array(12).fill(0)
      let temparr2 = new Array(12).fill(0)

      for (let i = 0; i < results.rows.length; i++) {
        if (results.rows.item(i).type_id === 1) {
          let idx = Number(results.rows.item(i).month)
          temparr1[idx - 1] = results.rows.item(i).total

        } else if (results.rows.item(i).type_id === 2) {
          let idx = Number(results.rows.item(i).month)
          temparr2[idx - 1] = results.rows.item(i).total

        }
      }
      temp1.push({
        labels: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
        datasets: [{
          data: temparr1
        }]
      })
      temp2.push({
        labels: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
        datasets: [{
          data: temparr2
        }]
      })
      res({ temp1, temp2 })
    })
  })

}
const chartApi = {
  outMoney,
  yearMoney
}

export default chartApi;