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

namespace MarketData.Helper
{
  public class MovingAverageHelperSheet
  {
    public MovingAverageHelperSheet()
    {
    }
    public static bool GenerateMovingAverageSheet(String strPathTemplateFile, String symbol)
    {
      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 companyName = PricingDA.GetNameForSymbol(symbol);
        DateGenerator dateGenerator = new DateGenerator();
        DateTime startDate = dateGenerator.GetPrevBusinessDay(DateTime.Now);
        String currentWorkingDirectory = Directory.GetCurrentDirectory();
        if (!File.Exists(strPathTemplateFile))
        {
          MDTrace.WriteLine(LogLevel.DEBUG,"Cannot locate " + strPathTemplateFile);
          return false;
        }
        MovingAverages movingAverages = MovingAverageGenerator.GenerateMovingAverages(symbol);
        String pathOutputFile = currentWorkingDirectory + "\\" + symbol + "-MA-" + Utility.DateTimeToStringMMHDDHYYYY(movingAverages.ThruDate);
        MDTrace.WriteLine(LogLevel.DEBUG,"Generating " + pathOutputFile);
        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 movingAverageChartObject = chartObjects.Item(1);    // yes, chart 1 is the fast line
        movingAverageChartObject.Chart.ChartTitle.Text = companyName + " (" + symbol + ")  " + Utility.DateTimeToStringMMHDDHYYYY(movingAverages.FromDate) + " - " + Utility.DateTimeToStringMMHDDHYYYY(movingAverages.ThruDate) + " MA(55,21,5)";
        Axis vertAxis = (Axis)movingAverageChartObject.Chart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
        vertAxis.MaximumScaleIsAuto = false;
        vertAxis.MaximumScale = GetMaxData(movingAverages);
        vertAxis.MinimumScaleIsAuto = false;
        vertAxis.MinimumScale = GetMinData(movingAverages);
        vertAxis.HasMajorGridlines = true;
        Axis horzAxis = (Axis)movingAverageChartObject.Chart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
        horzAxis.HasMajorGridlines = true;
        for (int index = 0; index < movingAverages.Count; index++)
        {
          MovingAverageElement movingAverageElement = movingAverages[index];
          worksheet.Cells[index + 1 + rowOffset, 1] = movingAverageElement.Symbol;
          worksheet.Cells[index + 1 + rowOffset, 2] = movingAverageElement.Date;
          worksheet.Cells[index + 1 + rowOffset, 3] = movingAverageElement.Close;
          worksheet.Cells[index + 1 + rowOffset, 4] = movingAverageElement.High;
          worksheet.Cells[index + 1 + rowOffset, 5] = movingAverageElement.Low;
          worksheet.Cells[index + 1 + rowOffset, 6] = movingAverageElement.MA55;
          worksheet.Cells[index + 1 + rowOffset, 7] = movingAverageElement.MA21;
          worksheet.Cells[index + 1 + rowOffset, 8] = movingAverageElement.MA5;
        }
        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 double GetMinData(MovingAverages movingAverages)
    {
      double minData = double.MaxValue;
      for (int index = 0; index < movingAverages.Count; index++)
      {
        MovingAverageElement movingAverageElement = movingAverages[index];
        if (movingAverageElement.Close < minData) minData = movingAverageElement.Close;
        if (movingAverageElement.High < minData) minData = movingAverageElement.High;
        if (movingAverageElement.Low < minData) minData = movingAverageElement.Low;
        if (movingAverageElement.MA55 < minData) minData = movingAverageElement.MA55;
        if (movingAverageElement.MA21 < minData) minData = movingAverageElement.MA21;
        if (movingAverageElement.MA5 < minData) minData = movingAverageElement.MA5;
      }
      return minData - (minData * .05);
    }
    private static double GetMaxData(MovingAverages movingAverages)
    {
      double maxData = 0;
      for (int index = 0; index < movingAverages.Count; index++)
      {
        MovingAverageElement movingAverageElement = movingAverages[index];
        if (movingAverageElement.Close > maxData) maxData = movingAverageElement.Close;
        if (movingAverageElement.High > maxData) maxData = movingAverageElement.High;
        if (movingAverageElement.Low > maxData) maxData = movingAverageElement.Low;
        if (movingAverageElement.MA55 > maxData) maxData = movingAverageElement.MA55;
        if (movingAverageElement.MA21 > maxData) maxData = movingAverageElement.MA21;
        if (movingAverageElement.MA5 > maxData) maxData = movingAverageElement.MA5;
      }
      return maxData + (maxData * .05);
    }
    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();
      }
    }
  }
}

