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 파일을 위치 시킴
});

function MoneyDB() {
  const [money, setMoney] = useState([]);
  const [expense, setExpense] = useState(0)
  const [income, setIncome] = useState(0)

  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 closeDatabase = async DB => {
    if (DB) {
      console.log('closing database ...');
      try {
        (await DB).close(
          () => {
            console.log('Database was closed successfully');
          },
          err => console.log(err),
        );
      } catch (error) {
        console.log(error);
      }
    } else {
      console.log('Database was not opened');
    }
  };

  const queryMoney = async tx => {
    console.log('Excuting user query');
    try {
      const [txn, results] = await tx.executeSql('SELECT * FROM Money');
      console.log('item length', results.rows.length);
      const temp = [];
      for (let i = 0; i < results.rows.length; i++) {
        const element = results.rows.item(i);
        temp.push(element);
        console.log('item ', element);
      }
      setMoney(temp);
    } catch (error) {
      console.log('error in query money', error);
    }
  };

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

  //수정 전 코드
  // const insertData = async () => {
  //   await db.transaction(async (tx) => {
  //     console.log("데이터 삽입하기");
  //     tx.executeSql('INSERT INTO Money (expense, income) VALUES (?,?);',
  //       [expense, income],
  //       () => { console.log("삽입 성공"); },
  //       (error) => console.log(error))
  //   })
  // }

  useEffect(() => {
    loadAndQueryDB();
    return () => {
      // closeDatabase(await db); // 컴포넌트 없어질 때 디비 닫기 Error!!!
    };
  }, []);

  let listViewItemSeparator = () => {
    return (
      <View style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }} />
    );
  };

  let listItemView = item => {
    console.log('item in list view', item);
    return (
      <View>
        <Text>Expense: {item.expense} Age: {item.income}</Text>
      </View>
    );
  };

  console.log('money', money);
  console.log(expense, income)
  return (
    <SafeAreaView>
      <Text>db test</Text>
      <View>
        <Text style={style.Font}>-데이터 입력 테스트</Text>
        <Text>expense</Text>
        <TextInput
          placeholder="expense"
          onChangeText={
            (expense) => setExpense(expense)
          }
        />
        <Text>income</Text>
        <TextInput
          placeholder="income"
          onChangeText={
            (income) => setIncome(income)
          }
        />
        <Button title='데이터 삽입하기' onPress={insertData} />
      </View>
      <View style={{ backgroundColor: 'gray' }}>
        <Text style={style.Font}>-데이터</Text>
        <View>
          <FlatList
            data={money}
            ItemSeparatorComponent={listViewItemSeparator}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({ item }) => listItemView(item)}
          />
        </View>
        <Button title='데이터 다시 불러오기' onPress={loadAndQueryDB} />
      </View>
    </SafeAreaView>
  );
}

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

export default MoneyDB