using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
using MarketData.DataAccess;
using MarketData.MarketDataModel;
using MarketData.Generator;
using MarketData.Utils;

namespace MarketData.Helper
{
  public class StochasticsSheetHelper
  {
    public StochasticsSheetHelper()
    {
    }
    public static bool GenerateStochasticsSheet(String strPathTemplateFile, String symbol, int dayCount,int periodN,int periodK)
    {
      Microsoft.Office.Interop.Excel.Application excelApp = null;
      Microsoft.Office.Interop.Excel.Workbook workbook = null;
      Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
      Microsoft.Office.Interop.Excel.Sheets worksheets = null;
      int rowOffset = 1;
      try
      {
        String currentWorkingDirectory = Directory.GetCurrentDirectory();
        if (!File.Exists(strPathTemplateFile))
        {
          MDTrace.WriteLine(LogLevel.DEBUG,"Cannot locate " + strPathTemplateFile);
          return false;
        }
        DateGenerator dateGenerator = new DateGenerator();
        DateTime startDate = dateGenerator.GetPrevBusinessDay(DateTime.Now);
        Prices prices = PricingDA.GetPrices(symbol, startDate, dayCount);
        if (null == prices || 0 == prices.Count)
        {
          MDTrace.WriteLine(LogLevel.DEBUG,"No prices for " + symbol);
          return false;
        }
        Price price = prices[0];
        String pathOutputFile = currentWorkingDirectory + "\\" + symbol + "-ST-" + Utility.DateTimeToStringMMHDDHYYYY(price.Date);
        MDTrace.WriteLine(LogLevel.DEBUG,"Generating " + pathOutputFile);
        String companyName = PricingDA.GetNameForSymbol(symbol);
        File.Delete(pathOutputFile + ".xlsx");
        excelApp = new Microsoft.Office.Interop.Excel.Application();
        excelApp.ScreenUpdating = false;
        workbook = excelApp.Workbooks.Open(strPathTemplateFile, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
        worksheets = workbook.Worksheets;
        worksheet = (Microsoft.Office.Interop.Excel.Worksheet)worksheets.get_Item("Sheet1");
        Microsoft.Office.Interop.Excel.ChartObjects chartObjects = worksheet.ChartObjects();
        Microsoft.Office.Interop.Excel.ChartObject chartObject = chartObjects.Item(1);
        chartObject.Chart.ChartTitle.Text = companyName + " (" + symbol + ")  " + Utility.DateTimeToStringMMHDDHYYYY(prices[prices.Count - 1].Date) + " Thru " + Utility.DateTimeToStringMMHDDHYYYY(price.Date)+" N="+periodN+", K="+periodK;
        Stochastics stochastics = StochasticsGenerator.GenerateStochastics(prices, periodN, periodK);
        if (null == stochastics)
        {
          MDTrace.WriteLine(LogLevel.DEBUG,"Error generating stochastics.");
          return false;
        }
        Axis vertAxis = (Axis)chartObject.Chart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
        vertAxis.HasMajorGridlines = true;
        Axis horzAxis = (Axis)chartObject.Chart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
        horzAxis.HasMajorGridlines = true;
        for (int index = 0; index < stochastics.Count; index++)
        {
          StochasticElement stochasticElement = stochastics[index];
          worksheet.Cells[index + 1 + rowOffset, 1] = stochasticElement.Date;
          worksheet.Cells[index + 1 + rowOffset, 2] = stochasticElement.Symbol;
          worksheet.Cells[index + 1 + rowOffset, 3] = stochasticElement.Open;
          worksheet.Cells[index + 1 + rowOffset, 4] = stochasticElement.High;
          worksheet.Cells[index + 1 + rowOffset, 5] = stochasticElement.Low;
          worksheet.Cells[index + 1 + rowOffset, 6] = stochasticElement.Close;
          worksheet.Cells[index + 1 + rowOffset, 7] = stochasticElement.LN;
          worksheet.Cells[index + 1 + rowOffset, 8] = stochasticElement.HN;
          worksheet.Cells[index + 1 + rowOffset, 9] = stochasticElement.HX;
          worksheet.Cells[index + 1 + rowOffset, 10] = stochasticElement.LX;
          worksheet.Cells[index + 1 + rowOffset, 11] = stochasticElement.PK;
          worksheet.Cells[index + 1 + rowOffset, 12] = stochasticElement.PD;
        }
        workbook.SaveAs(pathOutputFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Type.Missing, Type.Missing, Type.Missing);
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
        return false;
      }
      finally
      {
        if (null != worksheet) ReleaseObject(worksheet);
        if (null != worksheets) ReleaseObject(worksheets);
        if (null != workbook) ReleaseObject(workbook);
        excelApp.Quit();
      }
    }
    private static void ReleaseObject(object obj)
    {
      try
      {
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
        obj = null;
      }
      catch (Exception ex)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,ex.ToString());
        obj = null;
      }
      finally
      {
        GC.Collect();
      }
    }
  }
}