const fs = require('fs');
const csv = require('csv-parser');
const { getRates } = require('../helpers/rates');
const {
    convertDateToEpoch,
    convertEpochToDate
} = require('../helpers/epoch');

const results = [], amountStore = {};

async function calculate(file, tokens, date) {
    let tokenArr
    if(tokens) {
        tokenArr = tokens.split(',')
    }

    let dateToEpoch
    if(date){
        dateToEpoch = convertDateToEpoch(date);
    }
    let pick = 0
    fs.createReadStream(file)
        .pipe(csv())
        .on('data', (data) => {
            
            if(dateToEpoch){
                if(data.timestamp > dateToEpoch){
                    results.push(data);
                    pick++
                    console.log(pick)
                }
            }
            else{
                results.push(data);
            }
        })
        .on('end', async () => {
            const uniqueCoins = [...new Set(results.map(item => item.token))];
            if(!tokens){
                tokenArr = uniqueCoins
            }
            const USDConvStore = await getRates(tokenArr);

            function USDConvStoreFn(parentCurreny, value){
                const ans = value / USDConvStore[parentCurreny]
                return ans.toFixed(2)
            }
            
            uniqueCoins.forEach(coin => {
                amountStore[coin] = 0
            })

            results.map(result => {
                if (result.transaction_type == "DEPOSIT" && result.token in USDConvStore) {
                    result.amount = USDConvStoreFn(result.token, result.amount)
                    amountStore[result.token] += +result.amount
                }
                else if(result.transaction_type == "WITHDRAWAL" && result.token in USDConvStore) {
                    result.amount = USDConvStoreFn(result.token, result.amount)
                    amountStore[result.token] -= +result.amount
                }
            })

            Object.keys(amountStore).forEach(key => amountStore[key] === 0 && delete amountStore[key]);
            console.table(amountStore)
        });
}

module.exports = calculate