//-------------------------------------------------------------------------------------
// SID Monitor - Utility for Sudden Ionospheric Disturbances Monitoring Stations
// Copyright (C) 2006 - Lionel Loudet
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//-------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Globalization;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using WeifenLuo.WinFormsUI;

namespace SID_monitor
{
    public partial class NGDCReportView : Form
    {
        // UI configuration deserialization method
        private DeserializeDockContent m_deserializeDockContent;

        // all dockable panels
        public SIDEventsViewerDockablePanel sidEventsViewerDockablePanel = new SIDEventsViewerDockablePanel();
        public ViewReportParametersDockablePanel viewReportParametersDockablePanel = new ViewReportParametersDockablePanel();
        public ViewerDockablePanel viewerDockablePanel = new ViewerDockablePanel();
        public OutputTextBoxDockablePanel outputTextBoxDockablePanel = new OutputTextBoxDockablePanel();


        // global variables
        private static String[] NullStrings = new string[16] { String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty };
        private String[] ChannelsDS = new string[16]; // contains the list of dataset present in the database associated to the selected report

        public NGDCReportView()
        {
            m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);

            InitializeComponent();

            NullStrings.CopyTo(ChannelsDS, 0);

            // viewReportParametersDockablePanel
            this.viewReportParametersDockablePanel.GraphUpdateRequested += new System.EventHandler(this.GraphUpdateRequested);
            this.viewReportParametersDockablePanel.LoadReportRequested += new System.EventHandler(this.viewReportParametersDockablePanel_LoadReportRequested);
            this.viewReportParametersDockablePanel.ReportFileError += new System.EventHandler(this.viewReportParametersDockablePanel_ReportFileError);

            // sidEventsViewerDockablePanel
            this.sidEventsViewerDockablePanel.SelectionChanged += new System.EventHandler(this.GraphUpdateRequested);
            this.sidEventsViewerDockablePanel.AllowUserToAddRows = false;
            this.sidEventsViewerDockablePanel.ReadOnly = true;
            this.sidEventsViewerDockablePanel.EnableContextMenu = false;
            this.sidEventsViewerDockablePanel.RowHeadersVisible = true;
            this.sidEventsViewerDockablePanel.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            // viewerDockablePanel
            this.viewerDockablePanel.ShowHint = DockState.Document;
            this.viewerDockablePanel.GraphUpdateRequested += new System.EventHandler(this.GraphUpdateRequested);

        }

        #region NGDCReportView Methods

        /// <summary>
        /// Gets UI configuration
        /// </summary>
        private IDockContent GetContentFromPersistString(string persistString)
        {
            if (persistString == typeof(SIDEventsViewerDockablePanel).ToString())
                return sidEventsViewerDockablePanel;
            else if (persistString == typeof(ViewReportParametersDockablePanel).ToString())
                return viewReportParametersDockablePanel;
            else if (persistString == typeof(ViewerDockablePanel).ToString())
                return viewerDockablePanel;
            else if (persistString == typeof(OutputTextBoxDockablePanel).ToString())
                return outputTextBoxDockablePanel;
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Default configuration of the panels
        /// </summary>
        private void SetDefaultUI()
        {
            try
            {
                // default configuration: all panels visible
                // viewerDockablePanel
                this.viewerDockablePanel.Show(this.dockPanel);

                // outputTextBoxDockablePanel
                this.outputTextBoxDockablePanel.Show(this.dockPanel);

                // sidEventsViewerDockablePanel
                this.sidEventsViewerDockablePanel.Show(this.dockPanel);

                // viewReportParametersDockablePanel
                this.viewReportParametersDockablePanel.Show(this.dockPanel);
            }
            catch
            {
                MessageBox.Show("User Interface internal error.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void NGDCReportView_Load(object sender, EventArgs e)
        {
            // loads UI configuration
            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), SID_monitor.Properties.Settings.Default.ViewReportLayoutFile);
            if (File.Exists(configFile))
            {
                try
                {
                    dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
                }
                catch
                {
                    SetDefaultUI();
                }
            }
            else
            {
                SetDefaultUI();
            }

        }

        private void NGDCReportView_FormClosing(object sender, FormClosingEventArgs e)
        {
            // save UI config
            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), SID_monitor.Properties.Settings.Default.ViewReportLayoutFile);
            dockPanel.SaveAsXml(configFile);
        }

        #endregion


        #region Load File Method

        private void viewReportParametersDockablePanel_LoadReportRequested(object sender, EventArgs e)
        {
            LoadReport(this.viewReportParametersDockablePanel.ReportFilename);
        }

        /// <summary>
        /// Parse the given report file and:
        /// - fills in the event list
        /// - fills in the associated databases names
        /// </summary>
        private void LoadReport(String filename)
        {
            try
            {
                // read file --------------------------------------------------------------------------------------------------------------
                String ReportText = File.ReadAllText(filename, Encoding.ASCII);
                this.outputTextBoxDockablePanel.AddOutputTextMessage(" Reading report file \"" + filename + "\"\n");


                // search for the date of the report --------------------------------------------------------------------------------------
                Regex DateRegEx = new Regex("^\\s*Date:\\s*(?<Month>\\d\\d)/(?<Year>\\d\\d)\\s*$",
                              RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);

                Match DateMatch = DateRegEx.Match(ReportText);

                if (!DateMatch.Success)
                {
                    this.outputTextBoxDockablePanel.AddOutputTextErrorMessage(" Wrong report file format \"" + Path.GetFullPath(filename) + "\". Date field not found. Aborting...\n");
                    this.viewReportParametersDockablePanel_ReportFileError(this, new EventArgs());
                    return;
                }


                // search for the channels database name ----------------------------------------------------------------------------------
                Regex DatabaseRegEx = new Regex("^\\s*Database:\\s*(?<File>.+)\\s*$",
                              RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);

                Match DatabaseMatch = DatabaseRegEx.Match(ReportText);

                if (!DatabaseMatch.Success)
                {
                    this.outputTextBoxDockablePanel.AddOutputTextWarningMessage(" Wrong report file format \"" + Path.GetFullPath(filename) + "\". No Channels Database field. Ignoring...\n");
                }

                // fills in the associated database name and array of datasets
                if (!String.IsNullOrEmpty(GetChannelsDatabaseName(DatabaseMatch.Groups["File"].Value, DateMatch.Groups["Month"].Value, DateMatch.Groups["Year"].Value)))
                {
                    this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename = Path.GetFullPath(DatabaseMatch.Groups["File"].Value);
                    this.viewReportParametersDockablePanel.ShowSunEnabled = true;
                    this.viewReportParametersDockablePanel.ShowForecastEnabled = true;
                    ChannelsDS = GetDatasetsFromRRDToolDatabase(this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename, this.outputTextBoxDockablePanel.Handle);
                }
                else
                {
                    this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename = "No associated database file! ";
                    this.viewReportParametersDockablePanel.ShowSunEnabled = false;
                    this.viewReportParametersDockablePanel.ShowForecastEnabled = false;
                    for (int i = 0; i < ChannelsDS.Length; i++)
                    {
                        ChannelsDS[i] = String.Empty;
                    }

                }

                // search for the GOES database name --------------------------------------------------------------------------------------
                Regex GOESDatabaseRegEx = new Regex("^\\s*GOES\\s+Database:\\s*(?<File>.+)\\s*$",
                              RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);

                Match GOESDatabaseMatch = GOESDatabaseRegEx.Match(ReportText);

                if (!GOESDatabaseMatch.Success)
                {
                    this.outputTextBoxDockablePanel.AddOutputTextWarningMessage(" Wrong report file format. \"" + Path.GetFullPath(filename) + "\". No GOES database field. Ignoring...\n");
                }

                // fills in the associated GOES database name
                if (!String.IsNullOrEmpty(GetGOESDatabaseName(GOESDatabaseMatch.Groups["File"].Value, DateMatch.Groups["Month"].Value, DateMatch.Groups["Year"].Value)))
                {
                    this.viewReportParametersDockablePanel.LabelGOESDatabaseFilename = Path.GetFullPath(GOESDatabaseMatch.Groups["File"].Value);
                    this.viewReportParametersDockablePanel.ShowGOES10Enabled = true;
                    this.viewReportParametersDockablePanel.ShowGOES12Enabled = true;
                }
                else
                {
                    this.viewReportParametersDockablePanel.LabelGOESDatabaseFilename = "No associated GOES database file!";
                    this.viewReportParametersDockablePanel.ShowGOES10Enabled = false;
                    this.viewReportParametersDockablePanel.ShowGOES12Enabled = false;
                }


                // search for events ------------------------------------------------------------------------------------------------------
                Regex EventRegEx = new Regex("^40\\s+(?<Year>\\d\\d)(?<Month>\\d\\d)(?<Day>\\d\\d)\\s+(?<StartHour>\\d\\d)(?<StartMin>\\d\\d)(?<StartQual>[ DEU])(?<EndHour>\\d\\d)(?<EndMin>\\d\\d)(?<EndQual>[ DEU])(?<MaxHour>\\d\\d)(?<MaxMin>\\d\\d)(?<MaxQual>[ DEU])\\s+(?<Importance>1-|1[ ]|1\\+|2[ ]|2\\+|3[ ]|3\\+)\\s+(?<Definiteness>[012345])(?<StationCode>[a-zA-Z]{2}\\d{2})\\s+(?<ObsCode>[^\\s]{3,}).*$",
                                              RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);

                Match m;
                int nbMatches = 0; // events counter

                // Clears the events list
                this.sidEventsViewerDockablePanel.ClearDataTable();

                // fills in the events list for each event found in the report
                for (m = EventRegEx.Match(ReportText); m.Success; m = m.NextMatch())
                {
                    nbMatches++;

                    SIDEvents.DataTableEventsRow row = (SIDEvents.DataTableEventsRow)this.sidEventsViewerDockablePanel.NewRow();

                    row.Date = DateTime.ParseExact(m.Groups["Day"].Value + "/" + m.Groups["Month"].Value + "/" + m.Groups["Year"].Value, "dd/MM/yy", DateTimeFormatInfo.InvariantInfo).Date;

                    row.StartTime = row.Date.AddHours(Convert.ToInt32(m.Groups["StartHour"].Value)).AddMinutes(Convert.ToInt32(m.Groups["StartMin"].Value));
                    switch (m.Groups["StartQual"].Value)
                    {
                        case " ":
                            row.StartQualifier = "None";
                            break;
                        case "D":
                            row.StartQualifier = "After (D)";
                            break;
                        case "E":
                            row.StartQualifier = "Before (E)";
                            break;
                        case "U":
                            row.StartQualifier = "Uncertain (U)";
                            break;
                        default:
                            throw (new Exception("Invalid Start Time qualifier (" + m.Groups["StartQual"].Value + ")\n"));
                    }
                    // if endtime time is less than starttime, it is on the next day
                    DateTime endTime = row.Date.AddHours(Convert.ToInt32(m.Groups["EndHour"].Value)).AddMinutes(Convert.ToInt32(m.Groups["EndMin"].Value));
                    if (DateTime.Compare(row.StartTime, endTime) < 0)
                    {
                        endTime.AddDays(1);
                    }
                    row.EndTime = endTime;
                    switch (m.Groups["EndQual"].Value)
                    {
                        case " ":
                            row.EndQualifier = "None";
                            break;
                        case "D":
                            row.EndQualifier = "After (D)";
                            break;
                        case "E":
                            row.EndQualifier = "Before (E)";
                            break;
                        case "U":
                            row.EndQualifier = "Uncertain (U)";
                            break;
                        default:
                            throw (new Exception("Invalid End Time qualifier (" + m.Groups["StartQual"].Value + ")\n"));
                    }

                    // if maxtime time is less than maxtime, it is on the next day
                    DateTime maxTime = row.Date.AddHours(Convert.ToInt32(m.Groups["MaxHour"].Value)).AddMinutes(Convert.ToInt32(m.Groups["MaxMin"].Value));
                    if (DateTime.Compare(row.StartTime, maxTime) < 0)
                    {
                        maxTime.AddDays(1);
                    }
                    row.MaxTime = maxTime;
                    switch (m.Groups["MaxQual"].Value)
                    {
                        case " ":
                            row.MaxQualifier = "None";
                            break;
                        case "D":
                            row.MaxQualifier = "After (D)";
                            break;
                        case "E":
                            row.MaxQualifier = "Before (E)";
                            break;
                        case "U":
                            row.MaxQualifier = "Uncertain (U)";
                            break;
                        default:
                            throw (new Exception("Invalid Maximum Time qualifier (" + m.Groups["StartQual"].Value + ")\n"));
                    }

                    switch (m.Groups["Importance"].Value)
                    {
                        case "1-":
                            row.Importance = "1- (< 19 mn)";
                            break;
                        case "1 ":
                            row.Importance = "1 (19-25mn)";
                            break;
                        case "1+":
                            row.Importance = "1+ (26-32mn)";
                            break;
                        case "2 ":
                            row.Importance = "2 (33-45mn)";
                            break;
                        case "2+":
                            row.Importance = "2+ (46-85mn)";
                            break;
                        case "3 ":
                            row.Importance = "3 (86-125mn)";
                            break;
                        case "3+":
                            row.Importance = "3+ (>125mn)";
                            break;
                        default:
                            throw (new Exception("Invalid Importance Parameter (" + m.Groups["Importance"].Value + ")\n"));
                    }

                    switch (m.Groups["Definiteness"].Value)
                    {
                        case "0":
                            row.Definiteness = "0 (Questionable)";
                            break;
                        case "1":
                            row.Definiteness = "1 (Possible)";
                            break;
                        case "2":
                            row.Definiteness = "2 (Fair)";
                            break;
                        case "3":
                            row.Definiteness = "3 (Reasonable)";
                            break;
                        case "4":
                            row.Definiteness = "4 (Reasonably Definite)";
                            break;
                        case "5":
                            row.Definiteness = "5 (Definite)";
                            break;
                        default:
                            throw (new Exception("Invalid Definiteness Parameter (" + m.Groups["Definiteness"].Value + ")\n"));
                    }

                    row.StationCode = m.Groups["StationCode"].Value;

                    row.ObserverCode = m.Groups["ObsCode"].Value;


                    // add the new event to the datagrid
                    this.sidEventsViewerDockablePanel.AddDataTableEventsRow(row);

                } // for

                if (nbMatches > 1)
                {
                    this.outputTextBoxDockablePanel.AddOutputTextMessage(" Found " + nbMatches.ToString() + " events in report \"" + Path.GetFullPath(filename) + "\"\n");
                }
                else
                {
                    this.outputTextBoxDockablePanel.AddOutputTextMessage(" Found " + nbMatches.ToString() + " event in report \"" + Path.GetFullPath(filename) + "\"\n");
                }

                if (nbMatches == 0) // updates the graph if selection contains no event (to display a "no image" image)
                                    // if events are present, the selection changed event will update the graph.
                {
                    this.viewerDockablePanel.Image = SID_monitor.Properties.Resources.no_image_available_300;
                }
            }
            catch (Exception ex)
            {
                this.outputTextBoxDockablePanel.AddOutputTextErrorMessage(" Cannot parse report file \"" + filename +
                                                                          "\"\n*** " + ex.ToString().Split('\n')[0] + "\n");
                this.viewReportParametersDockablePanel_ReportFileError(this, new EventArgs());
            }

        }


        /// <summary>
        /// Tries to guess the channels database name associated with the report file.
        /// The following filenames are used:
        /// - the one from the report, as supplied in the filename variable
        /// - the file sid.MMYY.rrd where sid is the default filename obtained from the settings. MM and YY are obtained from the variables monthe and year.
        /// - the fie sid.rrd
        /// </summary>
        /// <returns>an existing filename or string.empty if none found</returns>
        private string GetChannelsDatabaseName(string filename, string month, string year)
        {
            String currentFilename;
            try // try with the filename supplied in the report file
            {
                currentFilename = Path.GetFullPath(filename);
                if (File.Exists(currentFilename))
                {
                    return currentFilename;
                }
            }
            catch
            {
            }
            try // try with the file sid.MMYY.rrd
            {
                currentFilename = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(filename), SID_monitor.Properties.Settings.Default.RRDToolChannelsSaveFilename + "." + month + year + ".rrd"));
                if (File.Exists(currentFilename))
                {
                    return currentFilename;
                }
            }
            catch
            {
            }
            try // try with the file sid.rrd
            {
                currentFilename = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(filename), SID_monitor.Properties.Settings.Default.RRDToolChannelsSaveFilename + ".rrd"));
                if (File.Exists(currentFilename))
                {
                    return currentFilename;
                }
            }
            catch
            {
            }
            return String.Empty;

        }

        /// <summary>
        /// Tries to guess the GOES database name associated with the report file.
        /// The following filenames are used:
        /// - the one from the report, as supplied in the filename variable
        /// - the file goes.MMYY.rrd where goes is the default filename obtained from the settings. MM and YY are obtained from the variables monthe and year.
        /// - the fie goes.rrd
        /// </summary>
        /// <returns>an existing filename or string.empty if none found</returns>
        private string GetGOESDatabaseName(string filename, string month, string year)
        {
            String currentFilename;
            try // try with the filename supplied in the report file
            {
                currentFilename = Path.GetFullPath(filename);
                if (File.Exists(currentFilename))
                {
                    return currentFilename;
                }
            }
            catch
            {
            }
            try // try with the file sid.MMYY.rrd
            {
                currentFilename = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(filename), SID_monitor.Properties.Settings.Default.RRDToolGOESSaveFilename + "." + month + year + ".rrd"));
                if (File.Exists(currentFilename))
                {
                    return currentFilename;
                }
            }
            catch
            {
            }
            try // try with the file sid.rrd
            {
                currentFilename = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(filename), SID_monitor.Properties.Settings.Default.RRDToolGOESSaveFilename + ".rrd"));
                if (File.Exists(currentFilename))
                {
                    return currentFilename;
                }
            }
            catch
            {
            }
            return String.Empty;

        }
        #endregion


        #region Graph Update Methods

        /// <summary>
        /// Updates the graph when event selection changes
        /// </summary>
        private void GraphUpdateRequested(object sender, EventArgs e)
        {

            if (!String.IsNullOrEmpty(this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename) && File.Exists(Path.GetFullPath(this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename)))
            {

                if (this.sidEventsViewerDockablePanel.SelectedRows.Count > 0)
                {
                    // check if the selected station code if present in the database
                    bool[] ChannelsToShow = new bool[16];
                    for (int i = 0; i < ChannelsDS.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(ChannelsDS[i]) && String.Equals(ChannelsDS[i], (string)this.sidEventsViewerDockablePanel.SelectedRows[0].Cells["StationCode"].Value))
                        {
                            ChannelsToShow[i] = true;
                        }
                        else
                        {
                            ChannelsToShow[i] = false;
                        }
                    }

                    // determines if the GOES data is to be displayed
                    bool[] GOESToShow;
                    string GOESfile = String.Empty;
                    try
                    {
                        if (File.Exists(Path.GetFullPath(this.viewReportParametersDockablePanel.LabelGOESDatabaseFilename)))
                        {
                            GOESfile = Path.GetFullPath(this.viewReportParametersDockablePanel.LabelGOESDatabaseFilename);
                            GOESToShow = new bool[3] { this.viewReportParametersDockablePanel.ShowGOES10Checked, this.viewReportParametersDockablePanel.ShowGOES11Checked, this.viewReportParametersDockablePanel.ShowGOES12Checked };
                        }
                        else
                        {
                            GOESfile = String.Empty;
                            GOESToShow = new bool[3] { false, false, false };
                        }
                    }
                    catch
                    {
                        GOESfile = String.Empty;
                        GOESToShow = new bool[3] { false, false, false };
                    }

                    if (Array.IndexOf(ChannelsToShow, true) >= 0) // at least, one channel to display
                    {

                        SIDMonitorDateTime startTime = new SIDMonitorDateTime(Convert.ToDateTime(this.sidEventsViewerDockablePanel.SelectedRows[0].Cells["Date"].Value).Date);
                        SIDMonitorDateTime endTime = startTime.AddDays(1).Date;

                        if (Path.Equals(Path.GetFullPath(this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename), Path.GetFullPath(SID_monitor.Properties.Settings.Default.RRDToolDatabase)))
                        {   // associated database is current database
                            this.viewerDockablePanel.GenerateGraph(Path.GetFullPath(this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename),
                                                      GOESfile,
                                                      startTime.UnixTime.ToString(),
                                                      endTime.UnixTime.ToString(),
                                                      startTime.WinTime.ToLongDateString(),
                                                      this.viewReportParametersDockablePanel.ShowSunChecked,
                                                      this.viewReportParametersDockablePanel.ShowForecastChecked,
                                                      SID_monitor.Properties.Settings.ChannelStationCodes,
                                                      SID_monitor.Properties.Settings.ChannelTitles,
                                                      SID_monitor.Properties.Settings.ChannelLineWidths,
                                                      SID_monitor.Properties.Settings.ChannelColors,
                                                      SID_monitor.Properties.Settings.ChannelDev1Colors,
                                                      SID_monitor.Properties.Settings.ChannelDev2Colors,
                                                      SID_monitor.Properties.Settings.ChannelDev3Colors,
                                                      ChannelsToShow,
                                                      SID_monitor.Properties.Settings.GOESTitles,
                                                      SID_monitor.Properties.Settings.GOESLineWidths,
                                                      SID_monitor.Properties.Settings.GOESColors,
                                                      GOESToShow);
                        }
                        else // associated database is not current database
                        {
                            this.viewerDockablePanel.GenerateGraph(Path.GetFullPath(this.viewReportParametersDockablePanel.LabelChannelsDatabaseFilename),
                                                      GOESfile,
                                                      startTime.UnixTime.ToString(),
                                                      endTime.UnixTime.ToString(),
                                                      startTime.WinTime.ToLongDateString(),
                                                      this.viewReportParametersDockablePanel.ShowSunChecked,
                                                      this.viewReportParametersDockablePanel.ShowForecastChecked,
                                                      ChannelsDS,
                                                      NullStrings,
                                                      SID_monitor.Properties.Settings.ChannelLineWidths,
                                                      SID_monitor.Properties.Settings.ChannelColors,
                                                      SID_monitor.Properties.Settings.ChannelDev1Colors,
                                                      SID_monitor.Properties.Settings.ChannelDev2Colors,
                                                      SID_monitor.Properties.Settings.ChannelDev3Colors,
                                                      ChannelsToShow,
                                                      SID_monitor.Properties.Settings.GOESTitles,
                                                      SID_monitor.Properties.Settings.GOESLineWidths,
                                                      SID_monitor.Properties.Settings.GOESColors,
                                                      GOESToShow);
                        }
                    }
                    else
                    {
                        this.viewerDockablePanel.Image = SID_monitor.Properties.Resources.no_image_available_300;
                    }

                }
            }
            else
            {
                this.viewerDockablePanel.Image = SID_monitor.Properties.Resources.no_image_available_300;
            }


        }

        #endregion


        /// <summary>
        /// Reads the datasets present in a given RRDTool database
        /// </summary>
        public static String[] GetDatasetsFromRRDToolDatabase(string filename, IntPtr outputTextBoxHandle)
        {
            String[] DSList = new string[16] { String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty };

            if (!String.IsNullOrEmpty(filename) && File.Exists(Path.GetFullPath(filename)))
            {
                String infoString = RRDToolConnection.ExecuteRRDTool("info \"" + Path.GetFullPath(filename) + "\" ", RRDToolProcess.ShowOptions.ErrorsOnly, outputTextBoxHandle);

                Regex datasetRegEx = new Regex("^ds\\[(?<DS>.+)\\][.]type.*$",
                                              RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
                Match m;

                int nbMatch = 0;

                for (m = datasetRegEx.Match(infoString); m.Success; m = m.NextMatch())
                {
                    if (!String.Equals(m.Groups["DS"].Value, "sun") && (Array.IndexOf(DSList, m.Groups["DS"].Value) < 0) && (nbMatch < DSList.Length))
                    {
                        DSList[nbMatch] = m.Groups["DS"].Value;
                        nbMatch++;
                    }

                }
                String[] returnDSList = new string[nbMatch];
                Array.Copy(DSList, 0, returnDSList, 0, nbMatch);
                return returnDSList;
            }
            else
            {
                return null;
            }
        }

        #region viewReportParametersDockablePanel Events Handling
        private void viewReportParametersDockablePanel_ReportFileError(object sender, EventArgs e)
        {
            // Clears the events list
            this.sidEventsViewerDockablePanel.ClearDataTable();

            // Clears the image
            this.viewerDockablePanel.Image = SID_monitor.Properties.Resources.no_image_available_300;
        }
        #endregion

        #region File Menu
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.viewReportParametersDockablePanel.buttonLoadReport_Click(sender, e);
        }

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

        #region View Menu
        private void reportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.viewReportParametersDockablePanel.IsDisposed)
            {
                this.viewReportParametersDockablePanel.Show(this.dockPanel);
                this.viewReportParametersDockablePanel.PanelPane.Activate();
            }
        }

        private void eventsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.sidEventsViewerDockablePanel.IsDisposed)
            {
                this.sidEventsViewerDockablePanel.Show(this.dockPanel);
                this.sidEventsViewerDockablePanel.PanelPane.Activate();
            }
        }

        private void graphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.viewerDockablePanel.IsDisposed)
            {
                this.viewerDockablePanel.Show(this.dockPanel);
                this.viewerDockablePanel.PanelPane.Activate();
            }
        }

        private void outputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.outputTextBoxDockablePanel.IsDisposed)
            {
                this.outputTextBoxDockablePanel.Show(this.dockPanel);
                this.outputTextBoxDockablePanel.PanelPane.Activate();
            }
        }
        #endregion

        #region Help Menu
        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, this.helpProvider.HelpNamespace, HelpNavigator.Topic, "view_report.htm");
        }

        private void indexToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Help.ShowHelpIndex(this, this.helpProvider.HelpNamespace);
        }

        private void searchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, this.helpProvider.HelpNamespace, HelpNavigator.Find, "");
        }
        #endregion 



    }
}