import React, { useState } from 'react'

import { BacktestCards } from '../../components/organism'
import type { Backtest, Candle, Position, Trade } from '../../generated/ManagingApi'
import { Toast } from '../../components/mollecules'

const BacktestUpload: React.FC = () => {
  const [backtestingResult, setBacktests] = useState<Backtest[]>([])

  const handleFileUpload = (event: any) => {
    let t = new Toast('Uploading backtest file')
    const file = event.target.files[0];
    const reader = new FileReader();

    if (file == null)
        return;

    reader.onload = (event) => {
      try {
        const json = JSON.parse(event.target.result);
        let backtest = MapBacktest(json)
        console.log(backtest)
        setBacktests((arr) => [...arr, backtest]);
        t.update("success", 'Backtest uploaded')
      } catch (error) {
        console.error('Error parsing JSON file:', error);
        t.update('error', 'Cannot parse file')
      }
    };

    reader.readAsText(file);
  };

  return (
    <div className="container mx-auto">
     <input type="file" accept=".json" onChange={handleFileUpload} />
      <BacktestCards list={backtestingResult} setBacktests={setBacktests} />
    </div>
  )
}

function MapBacktest(json: any){
    let backtest = {} as Backtest
    backtest.candles = MapCandles(json.Candles)
    backtest.accountName = json.AccountName
    backtest.botType = json.BotType
    backtest.fees = json.Fees
    backtest.finalPnl = json.FinalPnl
    backtest.growthPercentage = json.GrowthPercentage
    backtest.hodlPercentage = json.HodlPercentage
    backtest.moneyManagement = json.MoneyManagement
    backtest.optimizedMoneyManagement = json.OptimizedMoneyManagement
    backtest.positions = MapPositions(json.Positions)
    backtest.scenario = json.Scenario
    backtest.signals = json.Signals
    backtest.statistics = json.Statistics
    backtest.ticker = json.Ticker
    backtest.timeframe = json.Timeframe
    backtest.walletBalances = json.WalletBalances
    backtest.winRate = json.WinRate
    backtest.statistics = json.Statistics

    return backtest
}

function MapCandles(candlesInput: any): Candle[] {
  let candles = [] as Candle[]
  candlesInput.forEach( (c: any) => {
    let candle = {} as Candle
    candle.close = c.Close
    candle.high = c.High
    candle.low = c.Low
    candle.open = c.Open,
    candle.openTime = c.OpenTime
    candles.push(candle)
  });
  return candles
}

function MapPositions(positionsInput: any): Position[]{
  let positions = [] as Position[]
  positionsInput.forEach( 
    (p: any) => {
    let position = {} as Position
    position.date = p.Date
    position.identifier = p.Identifier
    position.open = MapTrade(p.Open)
    position.originDirection = p.OriginDirection
    position.stopLoss = MapTrade(p.StopLoss)
    position.takeProfit1 = MapTrade(p.TakeProfit1)
  });

  return positions
}

function MapTrade(openInput: any): Trade{
  let open = {} as Trade
  open.price = openInput.Price
  return open
}

export default BacktestUpload
