import { DEBUG, enablePromise, openDatabase } from 'react-native-sqlite-storage';
import { SafeAreaView, StyleSheet, Text, View, TextInput, FlatList, Button } from 'react-native';
import React, { useEffect, useState } from 'react';

DEBUG(true);
enablePromise(true);

const db = openDatabase({
  name: 'MyMoney',
  location: 'default',
  createFromLocation: '~MyMoney.db', // android/src/main/assets/TestDB.db 파일을 위치 시킴
});

const QueryFunc = async (Query) => {
  (await db).transaction(Query)
};

function InsertCat() {
  const [cat, setCat] = useState('')
  const [asset, setAsset] = useState('')

  console.log('money db')

  const populateDatabase = async DB => {
    await DB.transaction(queryMoney); // 반드시 (await db)를 해야 프라미스가 성공
  };

  const loadAndQueryDB = async () => {
    try {
      console.log('load and db query ....');
      await populateDatabase(await db);
    } catch (error) {
      console.log(error);
    }
  };

  const insertCategory = async () => {
    QueryFunc(async (tx) => {
      console.log("카테고리 정보 저장");
      await tx.executeSql('INSERT INTO categories (category_name) VALUES (?);',
        [cat],
        () => { console.log("카테고리 삽입 성공"); },
        (error) => console.log(error))
    })
  }

  const insertAsset = async () => {
    QueryFunc(async (tx) => {
      console.log("자산 정보 저장");
      await tx.executeSql('INSERT INTO assets_type (assets_name) VALUES (?);',
        [asset],
        () => { console.log("자산 삽입 성공"); },
        (error) => console.log(error))
    })
  }


  return (
    <SafeAreaView>
      <Text>db test</Text>
      <View>
        <Text style={style.Font}>-데이터 입력 테스트</Text>
        <Text>cat</Text>
        <TextInput
          placeholder="cat"
          onChangeText={
            (cat) => setCat(cat)
          }
        />
        <Text>asset</Text>
        <TextInput
          placeholder="asset"
          onChangeText={
            (asset) => setAsset(asset)
          }
        />
      </View>
      <Button title='카테고리 삽입하기' onPress={insertCategory} />
      <Button title='자산 삽입하기' onPress={insertAsset} />
    </SafeAreaView>
  );
}

const style = StyleSheet.create({
  Font: {
    fontSize: 24
  }
});

export default InsertCat