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

DEBUG(true);
enablePromise(true);

// const database_name = "MyMoney.db";
// const database_version = "1.0"
// const database_displayname = "SQLite Test Database";
// const database_size = 200000;

const db = openDatabase({
  name: 'MyMoney',
  location: 'default',
  createFromLocation: '~MyMoney.db',
});

function MoneyDB() {
  const [date, setDate] = useState('2021-01-01')
  const [category, setCategory] = useState(2)
  const [subcategory, setSubcategory] = useState(2)
  const [type, setType] = useState('우리')
  const [contents, setContents] = useState('경로')
  const [price, setPrice] = useState(1000)
  const [assetsId, setAssetsId] = useState()
  const [assetsname, setAssetsname] = useState()

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

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

  const getData = async tx => {
    console.log('데이터 가져오기');
    try {
      const [txn, results] = await tx.executeSql('SELECT * FROM money');
      console.log('results: ', results.rows.item(0));
    } catch (error) {
      console.log('error in getData', error);
    }
  }


  const createTable = async tx => {
    console.log('테이블 생성하기');
    try {
      const [txn, results] = await tx.executeSql('CREATE TABLE IF NOT EXISTS Test(' + 'Money INTEGER);');
      console.log("테이블 생성 성공 ");
    } catch (error) {
      console.log('error in createTable', error);
    }
  }

  const insertData = async () => {
    try {
      (await db).transaction((tx) => {
        console.log("데이터 삽입하기");
        tx.executeSql('INSERT INTO assets_type (assets_id, assets_name) VALUES (?,?);',
          [assetsId, assetsname],
          () => { console.log("삽입 성공"); },
          (error) => console.log(error))
      })
    } catch (error) {
      console.log('error in insertData', error);
    }
  }

  useEffect(() => {
    loadAndQueryDB();
  }, []);

  return (
    <>
      <SafeAreaView>
        <View>
          <Text>DB</Text>
          <Button title='데이터 가져오기' onPress={() => getData()} />
          <Button title='테이블 생성하기' onPress={() => createTable()} />

          <TextInput placeholder='assetsId' onChangeText={(assetsId) => setAssetsId(assetsId)} />
          <TextInput placeholder='assetsname' onChangeText={(assetsname) => setAssetsname(assetsname)} />

          <Button title='데이터 삽입하기' onPress={() => insertData()} />
        </View>
      </SafeAreaView>

    </>
  )
}


export default MoneyDB;