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

const selectAssetsType = async () => {
    const db = await getDb();
    return new Promise((resolve, reject) => {
        db.transaction(async (tx) => {
            const [txn, results] = await tx.executeSql('SELECT * FROM assets_type');
            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 });
                }
            }
            resolve(temp);
        })
    })
}

const deleteOption = async (table, data) => {
    const db = await getDb();
    const { id, name } = data
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            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) => {
            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]
    }
    return new Promise((resolve, reject) => {
        db.transaction((tx) => {
            tx.executeSql(insertQeury,
                queryData,
                (error) => console.log(error))
            resolve('데이터 삽입 카테고리 카테고리 완료');
        })
    })
};

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

export default editApi;