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

DEBUG(true);
enablePromise(true);

const getFullData = async () => {
  const db = await getDb();
  return new Promise((res, rej) => {
    db.transaction(async (tx) => {
      console.log('월간 데이터');
      const [txn, results] = await tx.executeSql('SELECT * FROM money WHERE date BETWEEN "2021-07-01" AND "2021-07-31"');
      const temp = [];
      for (let i = 0; i < results.rows.length; i++) {
        console.log('item check', results.rows.item(i));
        if (results.rows.item(i).type == '수입') {
          temp.push({ date: results.rows.item(i).date, type: { 'input': results.rows.item(i).price } })
        }
        if (results.rows.item(i).type == '지출') {
          temp.push({ date: results.rows.item(i).date, type: { 'output': results.rows.item(i).price } })
        }
      }
      console.log('temp1', temp)
      temp.sort(function (a, b) {
        return a.date < b.date ? -1 : a.date > b.date ? 1 : 0;
      })
      const temp2 = [temp[0]]
      for (let i = 1; i < temp.length; i++) {
        if (temp[i].date === temp[i-1].date) {
          let lastObj = temp2.pop()
          let newObj = lastObj.type
          for (const key in temp[i].type) {
            let data = 0
            if (newObj.hasOwnProperty(key)) {
              console.log('둘이 더할거임', temp[i].date, newObj[key], ' + ', temp[i].type[key], data)
              data = newObj[key] + temp[i].type[key]
              newObj[key] = data
            } else {
              newObj[key] = temp[i].type[key]
            }
            console.log('TETETET', temp[i].date, newObj)
          }
          temp2.push({ date: temp[i].date, type: newObj})
        } else {
          temp2.push(temp[i])
        }
      }
      console.log('temp2', temp2)
      res(temp2); 
    })
  })
}

const calApi = {
  getFullData
}

export default calApi;