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

DEBUG(true);
enablePromise(true);

const insertMoney = async (moneyData) => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql('INSERT INTO Money (type_id, date, contents, price, assets_id, category_id, subcategory_id) VALUES (?,?,?,?,?,?,?);',
                moneyData,
                (error) => console.log(error))
            resolve('데이터 삽입 완료');
        })
    })
};

const selectCategories = async (type_id) => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            const [txn, results] = await tx.executeSql(`SELECT * FROM categories WHERE type_id=${type_id}`);
            const temp = [];
            temp.push({id: 1, value:'기타'});
            for (let i = 0; i < 3*(Math.ceil((results.rows.length+1)/3))-1; i++) {
                if (i<results.rows.length){
                    const tempId = results.rows.item(i).category_id;
                    const tempName = results.rows.item(i).category_name;
                    temp.push({ id: tempId, value: tempName });
                } else {
                    temp.push({ id: 0, value: '' });
                }
            }
            resolve(temp);
        })
    })
}

const selectSubCategories = async () => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            const [txn, results] = await tx.executeSql('SELECT * FROM subcategories');
            const temp = [];
            for (let i = 0; i < results.rows.length; i++) {
                const tempId = results.rows.item(i).subcategory_id;
                const tempName = results.rows.item(i).subcategory_name;
                const tempCatId = results.rows.item(i).category_id;
                temp.push({ id: tempId, value: tempName, foreign_id: tempCatId });
            }
            resolve(temp);
        })
    })
}

const selectAssetsType = async () => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            const [txn, results] = await tx.executeSql('SELECT * FROM assets_type');
            const temp = [];
            for (let i = 0; i < 3*(Math.ceil((results.rows.length)/3)); i++) {
                if (i<results.rows.length){
                    const tempId = results.rows.item(i).assets_id;
                    const tempName = results.rows.item(i).assets_name;
                    temp.push({ id: tempId, value: tempName });
                } else {
                    temp.push({ id: 0, value: '' });
                }
            }
            resolve(temp);
        })
    })
}


const moneyApi = {
    insertMoney,
    selectCategories,
    selectSubCategories,
    selectAssetsType,
}

export default moneyApi;