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

DEBUG(true);
enablePromise(true);

const insertDept = async (deptData) => {
    const db = await getDb();
    const { date, loan, message, money, repayment } = deptData 
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql('INSERT INTO dept (repayment_date, loan, loan_name, principal, repayment) VALUES (?,?,?,?,?);',
                [date, loan, message, money, repayment], 
                (error) => console.log(error))
            resolve('데이터 삽입 완료');
        })
    })
};

const selectLoan = async (title) => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            const [txn, results] = await tx.executeSql(`SELECT * FROM dept WHERE loan ="${title}"`);
            const temp = [];
            for (let i = 0; i < results.rows.length; i++) {
                const tempId = results.rows.item(i).dept_id;
                const tempLoan = results.rows.item(i).loan;
                const tempPrincipal = results.rows.item(i).principal;
                const tempRepayment = results.rows.item(i).repayment;
                const tempRe_date = results.rows.item(i).repayment_date;
                const tempLoan_name = results.rows.item(i).loan_name;
                temp.push({ id: tempId, date: tempRe_date, loan: tempLoan, message: tempLoan_name, money: tempPrincipal, repayment: tempRepayment });
            }
            resolve(temp);

        })
    })
}

const deleteDept = async (id) => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql(`DELETE FROM dept WHERE dept_id = ${id}`)
            resolve('삭제완료');
        })
    })
}


const updateDept = async (deptData, id) => {
    const db = await getDb();
    const { date, message, money, repayment } = deptData
    console.log(date, message, id)
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql(`UPDATE dept set repayment_date =?, loan_name=?, principal=?, repayment=? where dept_id =${id};`,
                [date, message, money, repayment],
                (error) => console.log(error))
            resolve('데이터 변경 완료');
        })
    })
};

const deptApi = {
    insertDept,
    selectLoan,
    deleteDept,
    updateDept,
}

export default deptApi;