import React, { useState, useEffect } from 'react';
import ChartM from './ChartM';
import ChartY from './ChartY';
import chartApi from './db/chartData.api';
import ButtonsForm from './components/ButtonsForm';
import { View, Dimensions } 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 getDataM = async () => {
    try {
      const resdata = await chartApi.outMoney({ year: year, month: month })
      console.log('db res M', resdata)
      return resdata
    } catch (error) {
      console.log('error in getDataM', error)
    }
  }
  const getDataY = async () => {
    try {
      const resdata = await chartApi.yearMoney({ year: year })
      console.log('db res Y', resdata)
      setResDataY(resdata)

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

  const calPercentage = async () => {
    const resPrice = await getDataM()
    //console.log('어떻게 생겼니', resPrice)
    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)
  }

  useEffect(() => {
    getDataY()
    calPercentage()
  }, [])
  useEffect(() => {
    setResDataM([])
    calPercentage()
  }, [month])

  useEffect(() => {
    getDataY()
  }, [year])
  return (
    <>
      <View>
        <ButtonsForm
          onPress={(index) => setSelectedIndex(index)}
          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;
