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

DEBUG(true);
enablePromise(true);

const getFullData = 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 date, type_id, sum(price) as total from money where date BETWEEN "${getDateStr(thisFirst)}" and "${getDateStr(thisLast)}" group by date, type_id`);
      const temp = [];
      if (results.rows.length != 0) {
        if (results.rows.item(0).type_id === 1) {
          temp.push({ date: results.rows.item(0).date, type: { 'input': results.rows.item(0).total } })
        }
        if (results.rows.item(0).type_id === 2) {
          temp.push({ date: results.rows.item(0).date, type: { 'output': results.rows.item(0).total } })
        }
      }

      for (let i = 1; i < results.rows.length; i++) {
        if (results.rows.item(i).date === results.rows.item(i - 1).date) {
          temp.pop()
          let { 1: input, 2: output } = {
            [results.rows.item(i).type_id]: results.rows.item(i).total,
            [results.rows.item(i - 1).type_id]: results.rows.item(i - 1).total,
          }
          temp.push({ date: results.rows.item(i).date, type: { 'input': input, 'output': output } })
        } else {
          if (results.rows.item(i).type_id === 1) {
            temp.push({ date: results.rows.item(i).date, type: { 'input': results.rows.item(i).total } })
          }
          if (results.rows.item(i).type_id === 2) {
            temp.push({ date: results.rows.item(i).date, type: { 'output': results.rows.item(i).total } })
          }
        }
      }
      res(temp)
    })
  })
}

const detailData = async ({ findDate }) => {
  const db = await getDb();
  return new Promise((res, rej) => {
    db.transaction(async (tx) => {
      const [txn, results] = await tx.executeSql(`SELECT money.type_id, category_name, contents, price FROM money inner JOIN categories on money.category_id = categories.category_id WHERE date="${findDate}"`);
      const temp = [];
      for (let i = 0; i < results.rows.length; i++) {
        temp.push({ id: i, category: results.rows.item(i).category_name, contents: results.rows.item(i).contents, price: results.rows.item(i).price, type: results.rows.item(i).type_id })
      }
      res(temp);
    })
  })
}

const calApi = {
  getFullData,
  detailData
}

export default calApi;