﻿using System.Collections.Generic;
using Screener.Portfolio.Model.Brokerage.CommisionTerms;
using Screener.Portfolio.Model.Common;

namespace Screener.Portfolio.Model.Trade
{
    public class TradeBalance
    {
        public int Count { get; private set; }
        public CurrencyValue State { get; private set; }
        public decimal Efficiency { get; private set; }

        public List<TradeActionBalanceChange> Logs { get; } = new List<TradeActionBalanceChange>();

        public TradeBalance(Currency currency)
        {
            State = new CurrencyValue(0, currency);
        }

        public void RegisterChange(TradeStepBase step)
        {
            var volume = step.ActionRequest.Volume;

            if (volume.OrderType == TradeVolume.Type.Buy)
            {
                Count += volume.Count;
            }
            else
            {
                Count -= volume.Count;
            }
           
            var change = step.Change;
            Logs.Add(change);
            State += change.Value;
        }

        public void CalculateEfficiency()
        {
            var totalOutCome = 0m;

            foreach (var log in Logs)
            {
                if (log.Value.Value > 0m)
                {
                    totalOutCome += log.Value.Value;
                }
            }

            var totalChange = State.Value;

            Efficiency = totalChange / totalOutCome;
        }

        public override string ToString()
        {
            string countPostfix = Count > 0 ? " Count: " + Count : string.Empty;
            return State.ToString() + " Efficiency: " + (Efficiency * 100m).ToString("0.00") + countPostfix;
        }
    }
}