using System;
using System.IO;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using InvExplorer.ServiceReference1;

namespace InvExplorer
{
    /// <summary>
    /// Represents a command saves the current stock data to a CSV file.
    /// </summary>
    public class SaveDataCommand : ICommand
    {
        ViewModel _model;

        /// <summary>
        /// Initializes a new instance of a <see cref="SaveDataCommand"/>.
        /// </summary>
        /// <param name="model"><see cref="ViewModel"/> that owns this command.</param>
        public SaveDataCommand(ViewModel model)
        {
            _model = model;
        }
        /// <summary>
        /// Checks whether the command can be executed in the current model state,
        /// with the given parameter.
        /// </summary>
        public bool CanExecute(object parameter)
        {
            return true;
        }
        /// <summary>
        /// Event that fires when the command enabled state should change.
        /// </summary>
        public event EventHandler CanExecuteChanged;
        /// <summary>
        /// Saves the current stock data to a CSV file that can be loaded into Excel.
        /// </summary>
        public void Execute(object parameter)
        {
            var dlg = new SaveFileDialog();
            dlg.Filter = "Portfolio Data (*.csv)|*.csv";
            if (dlg.ShowDialog().Value)
            {
                using (var sw = new System.IO.StreamWriter(dlg.OpenFile()))
                {
                    SaveData(sw);
                }
            }
        }
        void SaveData(StreamWriter sw)
        {
            // get list of unique assets
            var dct = new Dictionary<Asset, IList<AssetPrice>>();
            foreach (var pf in _model.Portfolios)
            {
                foreach (var item in pf.Items)
                {
                    dct[item.Asset] = item.PriceHistory;
                }
            }

            // save header
            sw.WriteLine("Symbol, Date, Price");

            // save each asset
            foreach (var kv in dct)
            {
                SaveAsset(sw, kv.Key, kv.Value);
            }
        }
        void SaveAsset(StreamWriter sw, Asset asset, IList<AssetPrice> priceList)
        {
            sw.WriteLine("{0}: {1}", asset.Symbol, asset.Name);

            foreach (var price in priceList)
            {
                sw.WriteLine("{0}, {1:d}, {2}", asset.Symbol, price.Date, price.Price);
            }

            sw.WriteLine();
        }
    }
}
