import React, { useState, useEffect } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import ChartM from './ChartM';
import ChartY from './ChartY';
import chartApi from './db/chartData.api';
import ButtonsForm from './components/ButtonsForm';
import { View } from 'react-native';

const Analy = () => {

  const date = new Date();
  const [year, setYear] = useState(date.getFullYear());
  const [month, setMonth] = useState(date.getMonth());
  const [resDataM, setResDataM] = useState([]);
  const [resDataY, setResDataY] = useState([]);
  const [selectedIndex, setSelectedIndex] = useState(0);
  const todayM = date.getMonth();
  const todayY = date.getFullYear();

  const getDataM = async () => {
    try {
      const resdata = await chartApi.outMoney({ year: year, month: month })
      return resdata
    } catch (error) {
      console.log('error in getDataM', error)
    }
  }
  const getDataY = async () => {
    try {
      const resdata = await chartApi.yearMoney({ year: year })
      setResDataY(resdata)

    } catch (error) {
      console.log('error in getDataY', error)
    }
  }

  const calPercentage = async () => {
    const resPrice = await getDataM()
    let totalP = 0;

    for (let i = 0; i < resPrice.length; i++) {
      totalP = totalP + resPrice[i].total;
    }
    for (let j = 0; j < resPrice.length; j++) {
      resPrice[j].percentage = Math.round((resPrice[j].total / totalP) * 100);
    }
    setResDataM(resPrice)
  }

  useFocusEffect(
    React.useCallback(() => {
      setMonth(todayM)
      setYear(todayY)
      getDataY()
      calPercentage()
    }, [])
  );
  
  useEffect(() => {
    setResDataM([])
    calPercentage()
  }, [month])

  useEffect(() => {
    getDataY()
  }, [year])

  return (
    <>
      <View>
        <ButtonsForm
          onPress={(index) => { setSelectedIndex(index), setYear(todayY) }}
          selectedIndex={selectedIndex}
          group={["월간", "연간"]} />
      </View>
      <View>
        {
          selectedIndex === 0 ? <ChartM resDataM={resDataM} year={year} setYear={setYear} month={month} setMonth={setMonth} /> : <ChartY resDataY={resDataY} year={year} setYear={setYear} />
        }
      </View>
    </>
  )
}

export default Analy;
