﻿/*
 *   Copyright: 2011-2015, Mail2Voice
 *   Authors: Olivier "oliversleep" Villedieu, Laurent "lclaude" Claude, Matthieu "mhatz" Hazon, Diana "idiana" Ibanescu
 *   
 *   This file is part of Mail2Voice.
 *
 *   Mail2Voice 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 3 of the License, or
 *   (at your option) any later version.
 *
 *   Mail2Voice 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 Mail2Voice.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Mail2Voice
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Threading;
    using System.Timers;
    using System.Windows.Forms;
    using Mail2Voice.Panels;
    using Mail2Voice.Widgets;
    using Mail2VoiceCore;

    public partial class MainForm : Form
    {
        /***************************
         *      Attributes
         ***************************/
        private ReceiveControl receivePanel;
        private SendControl sendPanel;
        private ReceiveControl trashPanel;
        private ContactControl contactPanel;
        private ConfigurationControl configurationPanel;
        private HelpControl helpPanel;
        private QuitControl quitPanel;
        private KeyboardControl keyboardPanel;
        private List<UserControl> panels;
        private List<MainButton> mainButtons;

        private Thread receptionThread = null;
        private ReceiveObject receiveObj = null;

        private int resolutionWidth = 1024;
        private int resolutionHeight = 768;

        private bool state = false;

        // This timer is used to activate speech on mouse over on main buttons to say the button text (kind of preview)
        // It is stopped when played or when a main button is clicked
        private System.Timers.Timer mainButtonsHoverSpeechTimer;

        public bool EditingEmail { get; set; }

        /***************************
         *      Constructor
         ***************************/
        public MainForm(bool noupdate)
        {
            try
            {
                bool testConfig = true;
                this.InitializeComponent();

                // Delete mp3 files that are currently present in the directory
                FileObject.Singleton.DeleteMp3Files();

                this.Width = this.resolutionWidth;
                this.Height = this.resolutionHeight;

                this.Configure();

                if (this.TestConfiguration() == true) 
                {
                    this.sendButton.Enabled = true;
                    ConfigSettings.Singleton.Valid = true;
                    testConfig = true;
                }
                else  
                {
                    this.sendButton.Enabled = false;
                    ConfigSettings.Singleton.Valid = false;
                    testConfig = false;
                }

                this.BuildGui();
                if (testConfig == false)
                {
                    this.receivePanel.ClearInboxGrid();
                    this.receivePanel.ResetEmailDetails();
                    this.receivePanel.SetWarningInboxLabel(!testConfig);
                }

                this.mainButtonsHoverSpeechTimer = new System.Timers.Timer(1000);
                this.mainButtonsHoverSpeechTimer.Elapsed += new ElapsedEventHandler(this.OnMainButtonsHoverSpeech);

                FileObject.Singleton.DeleteAttachment(Constants.EMAIL_USER_FOLDER_INBOX_READ);
                FileObject.Singleton.DeleteAttachment(Constants.EMAIL_USER_FOLDER_INBOX_UNREAD);
                FileObject.Singleton.DeleteAttachment(Constants.EMAIL_USER_FOLDER_TRASH_READ);
                FileObject.Singleton.DeleteAttachment(Constants.EMAIL_USER_FOLDER_TRASH_UNREAD);

                this.trashButton.Visible = Convert.ToBoolean(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_EMAIL_ACTIVATE_TRASH));

                // If no email entered, we consider this is the first time M2V is started
                if (string.IsNullOrEmpty(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_EMAIL_LOGIN)))
                {
                    this.SwitchPanel(this.configurationPanel);
                    this.SwitchMainButton(this.configurationButton);
                }
                else
                {
                    this.SwitchPanel(this.receivePanel);
                    this.SwitchMainButton(this.inboxButton);

                    // If option enabled, open the help webpage to count current usage of Mail2Voice
                    if (Convert.ToBoolean(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_SEND_USAGE_STATS)))
                    {
                        WebBrowser browser = new WebBrowser();
                        browser.Navigate(@"http://www.mail2voice.org/aide.html?pk_campaign=m2v" + Application.ProductVersion);
                        browser.Dispose();
                    }
                }

                if (!noupdate)
                {
                    this.TimerVersion_Tick(null, null);
                }
                else
                {
                    this.timerVersion.Enabled = false;
                }

                this.EditingEmail = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }
        }

        /***************************
         *      Public methods
         ***************************/
        public void Configure()
        {
            if (!ConfigSettings.Singleton.Load(Application.StartupPath + Constants.CONFIG_FILE))
            {
                ConfigSettings.Singleton.SetConfigToDefault(Application.StartupPath + Constants.CONFIG_FILE);
            }

            ConfigSettings.Singleton.InitUserAccountFolders();

            // Init log component
            LogObject.Singleton.Init(Application.StartupPath);

            // Init speech component
            SpeechObject.Singleton.Init();
            SpeechObject.Singleton.SetVoice(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_LANG));

            // Init lang component
            LanguageObject.Singleton.SetRootFolder(Constants.CONFIG_LANGS_FOLDER);
            LanguageObject.Singleton.SetCurrentLang(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_TRANSLATION_LANG));

            // Init contacts component
            ContactsObject.Singleton.SetStorageFolder(Application.StartupPath);
            ContactsObject.Singleton.LoadFromXml();
            foreach (Contact contact in ContactsObject.Singleton.GetContactsList())
            {
                if (contact.Image == null) 
                {
                    contact.Image = Mail2Voice.properties.Resources.user_known;
                }
            }

            // Init mimes types
            FileObject.Singleton.Init(this.mimeTypesImageList);

            // Init IMAP
            if (this.receiveObj != null)
            {
                this.receiveObj.RequestStop();
                this.receiveObj = null;
            }

            if (this.receptionThread != null)
            {
                this.receptionThread.Abort();
                this.receptionThread = null;
            }

            this.receiveObj = new ReceiveObject();
            this.receptionThread = new Thread(this.receiveObj.EmailsPolling);
            this.receptionThread.IsBackground = true;
            this.receptionThread.Start();
        }

        public void UpdateConfiguration()
        {
            ConfigSettings.Singleton.InitUserAccountFolders();
            SpeechObject.Singleton.SetVoice(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_LANG));
            LanguageObject.Singleton.SetCurrentLang(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_TRANSLATION_LANG));
            this.TranslateApplication();

            this.receivePanel.ReadStoredEmails();

            this.sendPanel.UpdateDefaultMessage();
            this.configurationPanel.UpdateDefaultMessage();

            this.trashButton.Visible = Convert.ToBoolean(ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_EMAIL_ACTIVATE_TRASH));
            if (this.trashButton.Visible)
            {
                if (this.trashPanel == null)
                {
                    this.trashPanel = new ReceiveControl(Constants.TrashView) { Parent = this, Dock = DockStyle.Fill };
                    this.trashPanel.SetImageTypeMime(this.mimeTypesImageList);
                    this.trashPanel.ReadStoredEmails();
                }
            }

            if (this.TestConfiguration() == true) 
            {
              this.sendButton.Enabled = true;
                ConfigSettings.Singleton.Valid = true;
                this.receivePanel.SetWarningInboxLabel(false);
            }
            else
            {
              this.sendButton.Enabled = false;
              this.receivePanel.ClearInboxGrid();
              this.receivePanel.ResetEmailDetails();
              ConfigSettings.Singleton.Valid = false;
              this.receivePanel.SetWarningInboxLabel(true);
            }

            string test = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_SEND_CONTENT);

            // Init IMAP
            if (this.receiveObj != null)
            {
                this.receiveObj.RequestStop();
                this.receiveObj = null;
            }

            if (this.receptionThread != null)
            {
                this.receptionThread.Abort();
                this.receptionThread = null;
            }

            this.receiveObj = new ReceiveObject();
            this.receptionThread = new Thread(this.receiveObj.EmailsPolling);
            this.receptionThread.IsBackground = true;
            this.receptionThread.Start();
        }

        public void ShowHideKeyboard(bool show, Control ctrl, Control sentText)
        {
            if (show)
            {
                this.keyboardPanel.Show();
                this.keyboardPanel.SetSentText(sentText);
                this.keyboardPanel.Parent = ctrl;
                this.keyboardPanel.Left = 0;
                this.keyboardPanel.Top = 0;
                this.keyboardPanel.Height = ctrl.Height;
                this.keyboardPanel.Width = ctrl.Width;
                this.keyboardPanel.BringToFront();
            }
            else
            {
                this.keyboardPanel.Hide();
            }
        }

        public void SendEmail(string mailAddress)
        {
            this.SwitchMainButton(this.sendButton);
            this.SwitchPanel(this.sendPanel);
            this.sendPanel.SetEmail(mailAddress);
        }

        public void RefreshEmails(string view)
        {
            if (view == Constants.InboxView)
            {
                this.receivePanel.ReadStoredEmails();
            }
            else
            {
                this.trashPanel.ReadStoredEmails();
            }
        }

        public void UpdateContacts()
        {
            this.contactPanel.UpdateContent();
            this.sendPanel.UpdateContactsList();
            this.receivePanel.ReadStoredEmails();
            this.trashPanel.ReadStoredEmails();
        }

        public void AddContact(string email, string name)
        {
            this.ContactsButton_Click(null, null);
            this.contactPanel.PreFillContact(email, name);
        }

        #region "Display features"
        public void ForceDisplayReceptionPanel(bool initialization)
        {
            this.InboxButton_Click(null, null);
            if (initialization)
            {
                if (this.receivePanel != null)
                {
                    this.receivePanel.InitGrid();
                    this.receivePanel.ResetEmailDetails();
                }

                if (this.trashPanel != null)
                {
                    this.trashPanel.InitGrid();
                    this.trashPanel.ResetEmailDetails();
                }
            }
        }

        public void ForceDisplaySendPanel()
        {
            this.SendButton_Click(null, null);
        }

        public void OperationInProgress(bool status)
        {
            if (status)
            {
                this.operationPicture.Show();
            }
            else
            {
                this.operationPicture.Hide();
            }

            this.Refresh();
        }

        public void TranslateApplication()
        {
            LanguageObject.Singleton.Translate(this, this.Name);

            foreach (UserControl panel in this.panels)
            {
                if (panel != null)
                {
                    LanguageObject.Singleton.Translate(panel, panel.Name);
                }
            }
        }

        public void SetRecordMode(bool enabled)
        {
            this.inboxButton.Enabled = this.trashButton.Enabled = this.contactsButton.Enabled = this.helpButton.Enabled = this.configurationButton.Enabled = !enabled;
        }

        public void HandleMailTo(string address)
        {
            this.SwitchPanel(this.sendPanel);
            this.SwitchMainButton(this.sendButton);
            this.sendPanel.HandleMailTo(address);
        }

        /***************************
         *      Private methods
         ***************************/

        private bool TestConfiguration()
        {
            bool retVal = false;
            string inServerAddress = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_IMAP_ADDRESS);
            string inServerPort = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_IMAP_PORT);
            string imapSSL = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_IMAP_SSL);
            string emailPassword = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_EMAIL_PASSWORD);
            string emailLogin = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_EMAIL_LOGIN);
            string outServerAddress = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_SMTP_ADDRESS);
            string outServerPort = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_SMTP_PORT);
            
            if ((!string.IsNullOrEmpty(inServerAddress)) &&
                (!string.IsNullOrEmpty(inServerPort)) &&
                (!string.IsNullOrEmpty(imapSSL)) &&
                (!string.IsNullOrEmpty(emailPassword)) &&
                (!string.IsNullOrEmpty(outServerAddress)) &&
                (!string.IsNullOrEmpty(outServerPort)) &&
                (!string.IsNullOrEmpty(emailLogin)))
            {
                 int testImap;
                 bool testSmtp; 
                 testImap = LibraryObject.Singleton.TestImapServer(
                                  inServerAddress,
                                  Convert.ToInt32(inServerPort),
                                  Convert.ToBoolean(imapSSL),
                                  emailLogin,
                                  Encryption.Singleton.EncryptString(emailPassword, Constants.PASSWORD_KEY));
            
                 testSmtp = LibraryObject.Singleton.TestSmtpServer(outServerAddress, Convert.ToInt32(outServerPort));
            
                 if (testImap == 0 && testSmtp == true)
                 {
                    retVal = true;
                 }
            }

            return retVal;
        }

        private void SwitchMainButton(MainButton button)
        {
            // Reset main buttons to inactive
            this.inboxButton.Deactivate();
            this.sendButton.Deactivate();
            this.trashButton.Deactivate();
            this.contactsButton.Deactivate();
            this.configurationButton.Deactivate();
            this.helpButton.Deactivate();
            this.quitButton.Deactivate();

            button.Activate();
        }

        private void SwitchPanel(UserControl c)
        {
            try
            {
                // Cancel main button speech preview timer
                this.mainButtonsHoverSpeechTimer.Stop();

                // Stop current speech
                SpeechObject.Singleton.Stop();

                c.BringToFront();
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }
        }

        private void BuildGui()
        {
            // Set all styles to Dock = Fill
            try
            {
                if (this.receivePanel == null)
                {
                    this.receivePanel = new ReceiveControl(Constants.InboxView) { Parent = this, Dock = DockStyle.Fill };
                    this.receivePanel.BringToFront();
                    this.receivePanel.SetImageTypeMime(this.mimeTypesImageList);
                    this.receivePanel.ReloadConfiguration();
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            try
            {
                if (this.sendPanel == null)
                {
                    this.sendPanel = new SendControl() { Parent = this, Dock = DockStyle.Fill };
                    this.sendPanel.BringToFront();
                    this.sendPanel.SetImageTypeMime(this.mimeTypesImageList);
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            try
            {
                if (ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_EMAIL_ACTIVATE_TRASH).Equals(Constants.TRUE))
                {
                    if (this.trashPanel == null)
                    {
                        this.trashPanel = new ReceiveControl(Constants.TrashView) { Parent = this, Dock = DockStyle.Fill };
                        this.trashPanel.BringToFront();
                        this.trashPanel.SetImageTypeMime(this.mimeTypesImageList);
                    }
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            try
            {
                if (this.contactPanel == null)
                {
                    this.contactPanel = new ContactControl(this.sendPanel) { Parent = this, Dock = DockStyle.Fill };
                    this.contactPanel.BringToFront();
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            try
            {
                if (this.configurationPanel == null)
                {
                    this.configurationPanel = new ConfigurationControl() { Parent = this, Dock = DockStyle.Fill };
                    this.configurationPanel.BringToFront();
                    this.configurationPanel.Init();
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            try
            {
                if (this.helpPanel == null)
                {
                    this.helpPanel = new HelpControl() { Parent = this, Dock = DockStyle.Fill };
                    this.helpPanel.BringToFront();
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            try
            {
                if (this.quitPanel == null)
                {
                    this.quitPanel = new QuitControl() { Parent = this, Dock = DockStyle.Fill };
                    this.quitPanel.BringToFront();
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            try
            {
                if (this.keyboardPanel == null)
                {
                    this.keyboardPanel = new KeyboardControl();
                    this.keyboardPanel.Parent = this;
                    this.keyboardPanel.Hide();
                }
            }
            catch (Exception ex)
            {
                LogObject.Singleton.Write(new System.Diagnostics.StackFrame().GetMethod().Name, ex);
            }

            if (ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_EMAIL_ACTIVATE_TRASH).Equals(Constants.FALSE))
            {
                this.trashButton.Visible = false;
                if (this.trashPanel != null)
                {
                    this.trashPanel = null;
                }
            }
            else
            {
                this.trashButton.Visible = true;
                if (this.trashPanel != null) 
                {
                    this.trashPanel.ReloadConfiguration();
                }
            }
                
            this.panels = new List<UserControl>();
            this.panels.Add(this.receivePanel);
            this.panels.Add(this.sendPanel);
            this.panels.Add(this.trashPanel);
            this.panels.Add(this.contactPanel);
            this.panels.Add(this.configurationPanel);
            this.panels.Add(this.helpPanel);
            this.panels.Add(this.quitPanel);
            this.panels.Add(this.keyboardPanel);

            this.mainButtons = new List<MainButton>();
            this.mainButtons.Add(this.inboxButton);
            this.mainButtons.Add(this.sendButton);
            this.mainButtons.Add(this.trashButton);
            this.mainButtons.Add(this.contactsButton);
            this.mainButtons.Add(this.configurationButton);
            this.mainButtons.Add(this.helpButton);
            this.mainButtons.Add(this.quitButton);

            this.TranslateApplication();

            this.sendPanel.UpdateDefaultMessage();
            this.configurationPanel.UpdateDefaultMessage();
        }

        /********************************
         *      Private event handlers
         ********************************/   
        private void InboxButton_Click(object mainButtonSender, EventArgs e)
        {
            if (!this.inboxButton.IsActive())
            {
                this.receptionTimer.Enabled = false;
                this.SwitchMainButton(this.inboxButton);
                this.SwitchPanel(this.receivePanel);
            }
            else
            {
                this.receivePanel.ReadStoredEmails();
            }
        }

        private void SendButton_Click(object mainButtonSender, EventArgs e)
        {
            this.sendPanel.UpdateContent();
            this.SwitchMainButton(this.sendButton);
            this.SwitchPanel(this.sendPanel);
        }

        private void TrashButton_Click(object mainButtonSender, EventArgs e)
        {
            if (!this.trashButton.IsActive())
            {
                this.SwitchMainButton(this.trashButton);
                this.SwitchPanel(this.trashPanel);
            }
            else
            {
                this.trashPanel.ReadStoredEmails();
            }
        }

        private void ContactsButton_Click(object mainButtonSender, EventArgs e)
        {
            this.SwitchMainButton(this.contactsButton);
            this.SwitchPanel(this.contactPanel);
            this.contactPanel.UpdateContent();
        }

        private void ConfigurationButton_Click(object mainButtonSender, EventArgs e)
        {
            this.SwitchMainButton(this.configurationButton);
            this.SwitchPanel(this.configurationPanel);
        }

        private void HelpButton_Click(object mainButtonSender, EventArgs e)
        {
            this.SwitchMainButton(this.helpButton);
            this.SwitchPanel(this.helpPanel);
            this.helpPanel.OpenHelpPage();
        }

        private void QuitButton_Click(object mainButtonSender, EventArgs e)
        {
            this.SwitchMainButton(this.quitButton);

            if (this.EditingEmail)
            {
                this.quitPanel.ShowEditingEmailWarning();
            }
            else
            {
                this.quitPanel.HideEditingEmailWarning();
            }

            this.SwitchPanel(this.quitPanel);
        }

        private void MainButton_Hover(object mainButtonSender, EventArgs e)
        {
            // Start the main button speech preview timer
            if (ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_MAIN_BUTTONS_HOVER_SPEECH_PREVIEW).Equals(Constants.TRUE))
            {
                this.mainButtonsHoverSpeechTimer.Start();
            }
        }

        private void OnMainButtonsHoverSpeech(object source, ElapsedEventArgs e)
        {
            // Look for which main buttons has the cursor focus
            foreach (MainButton button in this.mainButtons)
            {
                if (button.HasCursorFocus())
                {
                    SpeechObject.Singleton.Speak(button.Text);
                }
            }
           
            // Stop the main button speech preview timer
            this.mainButtonsHoverSpeechTimer.Stop();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.EditingEmail == true)
            {
                e.Cancel = true;
                this.QuitButton_Click(null, null);
            }

            if (this.sendPanel != null)
            {
                this.sendPanel.StopRecording();
            }

            if (this.receiveObj != null)
            {
                this.receiveObj.RequestStop();
            }

            if (this.receptionThread != null)
            {
                this.receptionThread.Abort();
            }

            // Delete mp3 files that are currently present in the directory
            FileObject.Singleton.DeleteMp3Files();
        }
            
        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F2:
                    this.InboxButton_Click(null, null); 
                    break;
                case Keys.F3:
                    this.SendButton_Click(null, null);
                    break;
                case Keys.F4:
                    this.TrashButton_Click(null, null);
                    break;
                case Keys.F9:
                    this.ContactsButton_Click(null, null);
                    break;
                case Keys.F10:
                    this.ConfigurationButton_Click(null, null);
                    break;
                case Keys.F1:
                    this.HelpButton_Click(null, null);
                    break;
            }
            
            /* if (e.KeyCode == Keys.F2) { InboxButton_Click(null, null); return; }
            else if (e.KeyCode == Keys.F3) { SendButton_Click(null, null); return; }
            else if (e.KeyCode == Keys.F4) { TrashButton_Click(null, null); return; }
            else if (e.KeyCode == Keys.F9) { ContactsButton_Click(null, null); return; }
            else if (e.KeyCode == Keys.F10) { ConfigurationButton_Click(null, null); return; }
            else if (e.KeyCode == Keys.F1) { HelpButton_Click(null, null); return; }
            else if (e.KeyCode == Keys.Escape && quitButton.BackColor != Color.FromArgb(255, 255, 255)) { QuitButton_Click(null, null); return; } */

            if (this.inboxButton.IsActive())
            {
                switch (e.KeyCode)
                {
                    case Keys.PageUp:
                        this.receivePanel.UpButton_Click(null, null);
                        break;
                    case Keys.PageDown:
                        this.receivePanel.DownButton_Click(null, null);
                        break;
                    case Keys.F5:
                        this.receivePanel.SpeechSynthPlayButton_Click(null, null);
                        break;
                    case Keys.F6:
                        this.receivePanel.SpeechSynthPauseButton_Click(null, null);
                        break;
                    case Keys.F7:
                        this.receivePanel.SpeechSynthStopButton_Click(null, null);
                        break;
                    case Keys.O:
                        this.receivePanel.OpenAttachmentButton_Click(null, null);
                        break;
                    case Keys.Up:
                        if (e.Control)
                        {
                            this.receivePanel.PreviousAttachmentButton_Click(null, null);
                        }

                        break;
                    case Keys.Down:
                        if (e.Control)
                        {
                            this.receivePanel.NextAttachmentButton_Click(null, null);
                        }

                        break;
                    case Keys.Delete:
                        this.receivePanel.DeleteEmailButton_Click(null, null);
                        break;
                    case Keys.Enter:
                        if (e.Control)
                        {
                            this.receivePanel.ReplyToEmailButton_Click(null, null);
                        }

                        break;
                }
            }
            else if (this.sendButton.IsActive())
            {
                if (e.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.D0:
                            this.sendPanel.recipientEmailAddress.Focus();
                            break;
                        case Keys.T:
                            this.sendPanel.emailTitle.Focus();
                            break;
                        case Keys.M:
                            this.sendPanel.emailContent.Focus();
                            break;
                        case Keys.F17:
                            this.sendPanel.AddAttachmentButton_Click(null, null);
                            break;
                        case Keys.F16:
                            this.sendPanel.RemoveAttachmentButton_Click(null, null);
                            break;
                        case Keys.Up:
                            this.sendPanel.PreviousAttachmentButton_Click(null, null);
                            break;
                        case Keys.O:
                            this.sendPanel.OpenAttachmentButton_Click(null, null);
                            break;
                        case Keys.Down:
                            this.sendPanel.NextAttachmentButton_Click(null, null);
                            break;
                        case Keys.Delete:
                            this.sendPanel.CancelEmailButton_Click(null, null);
                            break;
                        case Keys.Enter:
                            this.sendPanel.SendEmailButton_Click(null, null);
                            break;
                    }
                }
                else
                {
                    switch (e.KeyCode)
                    {
                        case Keys.PageUp:
                            this.sendPanel.UpButton_Click(null, null);
                            break;
                        case Keys.PageDown:
                            this.sendPanel.DownButton_Click(null, null);
                            break;
                        case Keys.F8:
                            this.sendPanel.AudioRecordStartButton_Click(null, null);
                            break;
                        case Keys.F5:
                            this.sendPanel.AudioPlaybackPlayButton_Click(null, null);
                            break;
                        case Keys.F6:
                            this.sendPanel.AudioPlaybackPauseButton_Click(null, null);
                            break;
                        case Keys.F7:
                            this.sendPanel.AudioPlaybackStopButton_Click(null, null);
                            break;
                    }
                }
            }
            else if (this.trashButton.IsActive())
            {
                if (e.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.Up:
                            this.trashPanel.PreviousAttachmentButton_Click(null, null);
                            break;
                        case Keys.Down:
                            this.trashPanel.NextAttachmentButton_Click(null, null);
                            break;
                        case Keys.Enter:
                            this.trashPanel.ReplyToEmailButton_Click(null, null);
                            break;
                    }
                }
                else
                {
                    switch (e.KeyCode)
                    {
                        case Keys.PageUp:
                            this.trashPanel.UpButton_Click(null, null);
                            break;
                        case Keys.PageDown:
                            this.trashPanel.DownButton_Click(null, null);
                            break;
                        case Keys.F5:
                            this.trashPanel.SpeechSynthPlayButton_Click(null, null);
                            break;
                        case Keys.F6:
                            this.trashPanel.SpeechSynthPauseButton_Click(null, null);
                            break;
                        case Keys.F7:
                            this.trashPanel.SpeechSynthStopButton_Click(null, null);
                            break;
                        case Keys.O:
                            this.trashPanel.OpenAttachmentButton_Click(null, null);
                            break;
                        case Keys.Delete:
                            this.trashPanel.DeleteEmailButton_Click(null, null);
                            break;
                    }
                }
            }
            else if (this.contactsButton.IsActive())
            {
                if (e.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.I:
                            this.contactPanel.ChangeContactPhotoButton_Click(null, null);
                            break;
                        case Keys.N:
                            this.contactPanel.nameTextBox.Focus();
                            break;
                        case Keys.D0:
                            this.contactPanel.emailTextBox.Focus();
                            break;
                        case Keys.F17:
                            this.contactPanel.AddContactButton_Click(null, null);
                            break;
                        case Keys.M:
                            this.contactPanel.UpdateContactButton_Click(null, null);
                            break;
                        case Keys.Delete:
                            this.contactPanel.DeleteContactButton_Click(null, null);
                            break;
                        case Keys.Enter:
                            this.contactPanel.MailtoContactButton_Click(null, null);
                            break;
                    }
                }
                else
                {
                    switch (e.KeyCode)
                    {
                        case Keys.PageUp:
                            this.contactPanel.UpButton_Click(null, null);
                            break;
                        case Keys.PageDown:
                            this.contactPanel.DownButton_Click(null, null);
                            break;
                    }
                }

                // if (e.Control && e.KeyCode == Keys.Delete) this.contact.nonButton_Click(null, null);
                // if (e.Control && e.KeyCode == Keys.Enter) this.contact.ouiButton_Click(null, null);
            }
            else if (this.helpButton.IsActive())
            {
                if (e.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.H:
                            this.helpPanel.LoadHelpIndexButton_Click(null, null);
                            break;
                        case Keys.W:
                            this.helpPanel.GoToWebsiteButton_Click(null, null);
                            break;
                    }
                }
                else
                {
                    switch (e.KeyCode)
                    {
                        case Keys.F12:
                            this.helpPanel.AboutButton_Click(null, null);
                            break;
                    }
                }

                // if (e.KeyCode == Keys.PageDown) configuration.downButton_Click(null, null);
            }
            else if (this.quitButton.IsActive())
            {
                if (e.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.Enter:
                            this.quitPanel.YesButton_Click(null, null);
                            break;
                    }
                }
                else
                {
                    switch (e.KeyCode)
                    {
                        case Keys.Escape:
                            this.quitPanel.NoButton_Click(null, null);
                            break;
                    }
                }
            }
        }

        private void ReceptionTimer_Tick(object sender, EventArgs e)
        {
            if (!this.state)
            {
                this.inboxButton.Image = Mail2Voice.properties.Resources.inbox_BW;
                this.state = true;
            }
            else
            {
                this.inboxButton.Image = Mail2Voice.properties.Resources.inbox;
                this.state = false;
            }
        }

        // Timer to check if it's needed to launch version updater 
        private void TimerVersion_Tick(object sender, EventArgs e)
        {
            string updateVersion = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_UPDATE);
            bool isUpdate = false;

            if (bool.TryParse(updateVersion, out isUpdate))
            {
                if (isUpdate)
                {
                    string lastVersioning = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_UPDATE_LAST_CHECK);
                    DateTime lastVersioningDate = DateTime.MinValue;
                    if (DateTime.TryParse(lastVersioning, out lastVersioningDate))
                    {
                        string typeVersioning = ConfigSettings.Singleton.GetSettingValue(Constants.CONFIG_UPDATE);
                        int typeVersion = 0;
                        if (int.TryParse(typeVersioning, out typeVersion))
                        {
                            // J S M
                            bool needToUpdate = false;
                            if (typeVersion == 0)
                            {
                                if (lastVersioningDate.AddDays(1) < DateTime.Now)
                                {
                                    needToUpdate = true;
                                }
                            }
                            else if (typeVersion == 1)
                            {
                                if (lastVersioningDate.AddDays(7) < DateTime.Now)
                                {
                                    needToUpdate = true;
                                }
                            }
                            else if (typeVersion == 2)
                            {
                                if (lastVersioningDate.AddMonths(1) < DateTime.Now)
                                {
                                    needToUpdate = true;
                                }
                            }

                            if (needToUpdate)
                            {
                                ConfigSettings.Singleton.SetSettingValue(Constants.CONFIG_UPDATE_LAST_CHECK, DateTime.Now.ToString());
                                ConfigSettings.Singleton.SaveConfiguration();
                                if (File.Exists("./mail2voiceLauncher.exe"))
                                {
                                    ProcessStartInfo startInfo = new ProcessStartInfo();
                                    startInfo.FileName = "mail2voiceLauncher.exe";
                                    startInfo.Arguments = "noclose";
                                    Process.Start(startInfo);
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion "Display features"
    }
}
