
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, remained_money } = deptData //객체의 value값들을 가져옴
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            console.log("데이터 삽입하기");
            tx.executeSql('INSERT INTO dept (repayment_date, loan, loan_name, principal, repayment) VALUES (?,?,?,?,?);',
                [date, loan, message, money, remained_money], //가져온 value값들을 배열형식으로
                (error) => console.log(error))
            resolve('데이터 삽입 완료');
        })
    })
};





const selectLoan = async (title) => {
    const db = await getDb();
    console.log(title, "123")
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            console.log("내용 부르기");
            const [txn, results] = await tx.executeSql(`SELECT * FROM dept WHERE loan ="${title}"`);
            console.log('item length', results.rows.length);
            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, remained_money: tempRepayment });
            }
            resolve(temp);

        })
    })
}




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


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


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

export default deptApi;