using CCNetWrapper;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using _Application = Microsoft.Office.Interop.Word._Application;

namespace CCNetLogReader
{
    public partial class ReleaseNotes : Form
    {

        public MainWindow MainWindowParent { get; internal set; }

        public ReleaseNotes(List<ServerBuild> serverBuilds)
        {
            InitializeComponent();
            dgv_Projects.DataSource = null;
            serverBuilds.Sort((x, y) => string.CompareOrdinal(x?.ProjectName, y?.ProjectName));
            dgv_Projects.DataSource = serverBuilds.ToList();
            //dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dgv_Projects.Columns["ProjectName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        private void btn_OutputLocation_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog fd = new OpenFileDialog())
            {
                fd.Title = "Choose Release Note DOCX";

                fd.Filter = "Release Notes (*.docx)|*.docx|All Files (*.*)|*.*";

                var result = fd.ShowDialog();

                if (result == DialogResult.OK)
                {
                    txt_Output.Text = fd.FileName;
                }
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txt_ReleaseVersion.Text) && !string.IsNullOrEmpty(txt_Output.Text))
            {
                docx_write();
            }
            else if (string.IsNullOrEmpty(txt_ReleaseVersion.Text))
            {
                MessageBox.Show("No version number entered.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region fileIOFunctions
        private void docx_write()
        {
            string projectHeading = "";
            object oMissing = System.Reflection.Missing.Value;
            object oFileName = txt_Output.Text;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
            object oStartofDoc = "\\startofdoc"; /* \startofdoc is a predefined bookmark */
            object oProjectName = new object();

            //Start Word and create a new document.
            _Application oWord;
            _Document oDoc;
            try
            {
                oWord = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = true;
            }
            catch
            {
                MessageBox.Show("An error occured opening Word.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                oDoc = oWord.Documents.Open(ref oFileName, ref oMissing, ref oMissing, ref oMissing,
                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }
            catch
            {
                MessageBox.Show("An error occured opening the release notes DOCX file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                return;
            }


            //Heading paragraph
            Paragraph oPara1;
            Object oStartRange = oDoc.Bookmarks.get_Item(ref oStartofDoc).Range;
            oPara1 = oDoc.Content.Paragraphs.Add(ref oStartRange);
            object oStyle = WdBuiltinStyle.wdStyleHeading1;  // set HEADING1 built-in style
            oPara1.Range.set_Style(ref oStyle);
            oPara1.Range.Text = projectHeading + " " + txt_ReleaseVersion.Text +
                " – Released " + dtp_ReleaseDate.Text + "\n";

            //Release notes paragraph
            Paragraph oPara2;
            oStartRange = oPara1.Range;
            oPara2 = oDoc.Content.Paragraphs.Add(ref oStartRange);
            oStyle = WdBuiltinStyle.wdStyleListNumber; // set NUMBER LIST built-in style            
            oPara2.Format.set_Style(ref oStyle);
            oPara2.Range.Text = outputStringBuilder.ToString(); //inject xml output into paragraph     
        }
        #endregion

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        StringBuilder outputStringBuilder = new StringBuilder();
        private void dgv_Projects_SelectionChanged(object sender, EventArgs e)
        {
            var logDir = MainWindow.PROJECT_LOG_DIR;
            var projLogs = new List<ProjectLog>();
            var max = int.MinValue;
            var min = int.MaxValue;
            var buildNumber = string.Empty;
            dgv_Projects.Enabled = false;
            outputStringBuilder = new StringBuilder();
            var fbs = new List<int>();
            foreach (DataGridViewRow selRow in dgv_Projects.SelectedRows)
            {
                var projName = selRow.Cells["ProjectName"].Value.ToString();
                if (File.Exists($"{logDir}{projName}.xml"))
                {
                    var curProjLog = MainWindowParent.DeSerializeObject<CCNetWrapper.ProjectLog>($"{logDir}{projName}.xml");
                    
                    curProjLog.BuildLogs.ForEach(x =>
                    {
                        if (x.GetMinorBuildNumber() < min)
                        {
                            min = x.GetMinorBuildNumber();
                        }
                        if (x.GetMinorBuildNumber() > max)
                        {
                            buildNumber = x.BuildNumber;
                            max = x.GetMinorBuildNumber();
                        }
                        
                        if (!string.IsNullOrEmpty(x.Fogbugz) && !string.IsNullOrEmpty(x.ReleaseNote))
                        {
                            var fbNum = int.Parse(x.Fogbugz);
                            if (!fbs.Contains(fbNum))
                            {
                                fbs.Add(fbNum);
                                outputStringBuilder.AppendLine($"MS{x.Fogbugz}. {x.ReleaseNote}");
                            }
                        }
                        
                    });
                    projLogs.Add(curProjLog);
                }
            }
            lbl_MinorStart.Text = min.ToString();
            txt_Start.Text = min.ToString();

            lbl_MinorEnd.Text = max.ToString();
            txt_End.Text = max.ToString();
            txt_ReleaseVersion.Text = buildNumber;

            dgv_Projects.Enabled = true;
        }

        private void ReleaseNotes_Load(object sender, EventArgs e)
        {

        }
    }
}
