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

DEBUG(true);
enablePromise(true);

const insertMemo = async (memoData) => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            console.log("데이터 삽입하기");
            tx.executeSql('INSERT INTO memo (memo_date, message) VALUES (?,?);',
                [memoData.date, memoData.message],
                (error) => console.log(error))
            resolve('데이터 삽입 완료');
        })
    })
};

const selectMemo = async () => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            console.log("내용 부르기");
            const [txn, results] = await tx.executeSql('SELECT * FROM memo');
            console.log('item length', results.rows.length);
            const temp = [];
            for (let i = 0; i < results.rows.length; i++) {
                const tempId = results.rows.item(i).memo_id;
                const tempDate = results.rows.item(i).memo_date;
                const tempMsg = results.rows.item(i).message;
                temp.push({ id: tempId, date: tempDate, message: tempMsg });
            }
            console.log(temp)
            resolve(temp);
        })
    })
}

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

const updateMemo = async (memoData, id) => {
    const db = await getDb();
    const { date, message } = memoData
    console.log(date, message, id)
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            console.log("데이터 수정하기");
            tx.executeSql(`UPDATE memo set memo_date =?, message =? where memo_id =${id};`,
                [date, message],
                (error) => console.log(error))
            resolve('데이터 변경 완료');
        })
    })
};

// 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 memoApi = {
    insertMemo,
    selectMemo,
    deleteMemo,
    updateMemo,
}

export default memoApi;