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

DEBUG(true);
enablePromise(true);

const CAT_LIMIT_ID = 14
const ASSET_LIMIT_ID = 10

const selectCategories = async (type_id) => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            console.log("카테고리 부르기");
            const [txn, results] = await tx.executeSql(
                `select cat.category_id, category_name, subcat_id, subcat_name from categories as cat 
                left join ( 
                    SELECT category_id, 
                        group_concat(subcategory_id, '|') as subcat_id, 
                        group_concat(subcategory_name, '|') as subcat_name
                    from subcategories group by category_id
                ) as subcat
                on cat.category_id=subcat.category_id 
                where cat.type_id='${type_id}'`
            );
            console.log('item length', results.rows.length);
            const temp = [];
            for (let i = 0; i < results.rows.length; i++) {
                const tempId = results.rows.item(i).category_id;
                const tempName = results.rows.item(i).category_name;
                let deletable = (tempId < CAT_LIMIT_ID) ? false : true;
                const tempSubOptions = [];
                if (results.rows.item(i).subcat_id) {
                    const tempSubId = results.rows.item(i).subcat_id.split('|');
                    const tempSubValue = results.rows.item(i).subcat_name.split('|');
                    for (let i = 0; i < tempSubId.length; i++) {
                        tempSubOptions.push({ id: tempSubId[i], value: tempSubValue[i], foreign_id: tempId });
                    }
                }
                temp.push({ id: tempId, value: tempName, deletable: deletable, subOptions: tempSubOptions });
            }
            console.log(temp)
            resolve(temp);
            // console.log("카테고리 부르기");
            // const [txn, results] = await tx.executeSql(`SELECT * FROM categories WHERE type_id=${type_id}`);
            // console.log('item length', results.rows.length);
            // const temp = [];
            // for (let i = 0; i < results.rows.length; i++) {
            //     const tempId = results.rows.item(i).category_id;
            //     const tempName = results.rows.item(i).category_name;
            //     if (tempId < CAT_LIMIT_ID) {
            //         temp.push({ id: tempId, value: tempName, deletable: false });
            //     } else {
            //         temp.push({ id: tempId, value: tempName, deletable: true });
            //     }
            // }
            // console.log(temp)
            // resolve(temp);
        })
    })
}

const selectAssetsType = async () => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            console.log("자산 유형 부르기");
            const [txn, results] = await tx.executeSql('SELECT * FROM assets_type');
            console.log('item length', results.rows.length);
            const temp = [];
            for (let i = 0; i < results.rows.length; i++) {
                const tempId = results.rows.item(i).assets_id;
                const tempName = results.rows.item(i).assets_name;
                if (tempId < ASSET_LIMIT_ID) {
                    temp.push({ id: tempId, value: tempName, deletable: false });
                } else {
                    temp.push({ id: tempId, value: tempName, deletable: true });
                }
            }
            console.log(temp)
            resolve(temp);
        })
    })
}

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

const updateOption = async (table, data) => {
    const db = await getDb();
    const { id, name, value } = data
    console.log(table, id, value)
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            console.log("데이터 수정하기");
            tx.executeSql(`UPDATE ${table} set ${name}_name =? where ${name}_id =${id};`,
                [value],
                (error) => console.log(error))
            resolve(`${name} 데이터 변경 완료`);
        })
    })
};

const addOption = async (table, data) => {
    const db = await getDb();
    const { name, value, foreign_name = null, foreign_id } = data;
    let insertQeury = '';
    let queryData = [];
    if (foreign_name === null) {
        insertQeury = `INSERT INTO ${table} (${name}_name) VALUES (?);`
        queryData = [value]
    } else {
        insertQeury = `INSERT INTO ${table} (${name}_name, ${foreign_name}_id) VALUES (?,?);`
        queryData = [value, foreign_id]
    }
    // console.log(insertQuery, queryData)
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            console.log("데이터 삽입하기");
            tx.executeSql(insertQeury,
                queryData,
                (error) => console.log(error))
            resolve('데이터 삽입 카테고리 카테고리 완료');
        })
    })
};

const editApi = {
    selectCategories,
    selectAssetsType,
    deleteOption,
    updateOption,
    addOption,
}

export default editApi;