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 BollingerBandSheetHelper
  {
    public BollingerBandSheetHelper()
    {
    }
    public static bool GenerateBollingerBandSheet(String strPathTemplateFile,String symbol,int movingAverageDays,int historicalDays)
    {
      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,historicalDays);
        if (null == prices || 0 == prices.Count)
        {
          MDTrace.WriteLine(LogLevel.DEBUG,"No prices for "+symbol);
          return false;
        }
        Price price = prices[0];
        String pathOutputFile = currentWorkingDirectory + "\\" + symbol + "-BB-" + 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);
        BollingerBands bollingerBands = BollingerBandGenerator.GenerateBollingerBands(prices, movingAverageDays);
        Axis vertAxis = (Axis)chartObject.Chart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
        vertAxis.MaximumScaleIsAuto = false;
        vertAxis.MaximumScale = GetMaxData(bollingerBands); 
        vertAxis.MinimumScaleIsAuto = false;
        vertAxis.MinimumScale = GetMinData(bollingerBands);
        vertAxis.HasMajorGridlines = true;
        Axis horzAxis = (Axis)chartObject.Chart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
        horzAxis.HasMajorGridlines = true;
        for (int index = 0; index < bollingerBands.Count; index++)
        {
          BollingerBandElement bollingerBandElement = bollingerBands[index];
          worksheet.Cells[index + 1 + rowOffset, 1] = bollingerBandElement.Date;
          worksheet.Cells[index + 1 + rowOffset, 2] = bollingerBandElement.Symbol;
          worksheet.Cells[index + 1 + rowOffset, 3] = bollingerBandElement.Open;
          worksheet.Cells[index + 1 + rowOffset, 4] = bollingerBandElement.High;
          worksheet.Cells[index + 1 + rowOffset, 5] = bollingerBandElement.Low;
          worksheet.Cells[index + 1 + rowOffset, 6] = bollingerBandElement.Close;
          worksheet.Cells[index + 1 + rowOffset, 7] = bollingerBandElement.Volume;
          worksheet.Cells[index + 1 + rowOffset, 8] = bollingerBandElement.SMAN;
          worksheet.Cells[index + 1 + rowOffset, 9] = bollingerBandElement.StDevN;
          worksheet.Cells[index + 1 + rowOffset, 10] = bollingerBandElement.K;
          worksheet.Cells[index + 1 + rowOffset, 11] = bollingerBandElement.L;
          worksheet.Cells[index + 1 + rowOffset, 12] = bollingerBandElement.KL1;
          worksheet.Cells[index + 1 + rowOffset, 13] = bollingerBandElement.LP1;
        }
        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(BollingerBands bollingerBands)
    {
      double minData = double.MaxValue;
      for (int index = 0; index < bollingerBands.Count; index++)
      {
        BollingerBandElement bollingerBandElement = bollingerBands[index];
        if(bollingerBandElement.Open<minData)minData=bollingerBandElement.Open;
        if(bollingerBandElement.High<minData)minData=bollingerBandElement.High;
        if(bollingerBandElement.Low<minData)minData=bollingerBandElement.Low;
        if (bollingerBandElement.K < minData) minData = bollingerBandElement.K;
        if (bollingerBandElement.L < minData) minData = bollingerBandElement.L;
        if (bollingerBandElement.KL1 < minData) minData = bollingerBandElement.KL1;
        if (bollingerBandElement.LP1 < minData) minData = bollingerBandElement.LP1;
      }
      return minData-(minData*.05);
    }
    private static double GetMaxData(BollingerBands bollingerBands)
    {
      double maxData = 0;
      for (int index = 0; index < bollingerBands.Count; index++)
      {
        BollingerBandElement bollingerBandElement = bollingerBands[index];
        if (bollingerBandElement.Open > maxData) maxData = bollingerBandElement.Open;
        if (bollingerBandElement.High > maxData) maxData = bollingerBandElement.High;
        if (bollingerBandElement.Low > maxData) maxData = bollingerBandElement.Low;
        if (bollingerBandElement.K > maxData) maxData = bollingerBandElement.K;
        if (bollingerBandElement.L > maxData) maxData = bollingerBandElement.L;
        if (bollingerBandElement.KL1 > maxData) maxData = bollingerBandElement.KL1;
        if (bollingerBandElement.LP1 > maxData) maxData = bollingerBandElement.LP1;
      }
      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();
      }
    }
  }
}