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) => {
            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) => {
            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 });
            }
            resolve(temp);
        })
    })
}

const deleteMemo = async (id) => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            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) => {
            tx.executeSql(`UPDATE memo set memo_date =?, message =? where memo_id =${id};`,
                [date, message],
                (error) => console.log(error))
            resolve('데이터 변경 완료');
        })
    })
};

const memoApi = {
    insertMemo,
    selectMemo,
    deleteMemo,
    updateMemo,
}

export default memoApi;