using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Corp3s.Controls
{
    public class CustomTextBoxControl : TextBox
    {
        private EventHandler m_eNumericEntered = null;
        private EventHandler m_eNumericCanceled = null;

        private static Input.KeypadControl m_Keypad = null;
        
        public CustomTextBoxControl()
            : base()
        {
#if !DESIGN
            if (Environment.OSVersion.Platform != PlatformID.WinCE)
                return;

            if (m_Keypad == null)
                m_Keypad = new Corp3s.Controls.Input.KeypadControl();
#endif
        }        

        private void HideKeypad()
        {            
            if (Environment.OSVersion.Platform != PlatformID.WinCE)
                return;

            m_Keypad.OnEntered -= new EventHandler(OnEnteredHandler);
            m_Keypad.OnCanceled -= new EventHandler(OnCanceledHandler);

            if (m_Keypad == null)
                return;

            Form form = TopLevelControl as Form;
            form.Controls.Remove(m_Keypad);            
        }

        private void ShowKeypad()
        {
            if (Environment.OSVersion.Platform != PlatformID.WinCE)
                return;

            m_Keypad.OnEntered += new EventHandler(OnEnteredHandler);
            m_Keypad.OnCanceled += new EventHandler(OnCanceledHandler);

            m_Keypad.Show(TopLevelControl as Form, this.Text);
        }

        protected override void OnGotFocus(EventArgs e)
        {
            base.OnGotFocus(e);
            ShowKeypad();
        }

        void OnCanceledHandler(object sender, EventArgs e)
        {
            if (Environment.OSVersion.Platform != PlatformID.WinCE)
                return;

            HideKeypad();
            if (m_eNumericCanceled != null)
                m_eNumericCanceled(sender, e);

            
        }

        void OnEnteredHandler(object sender, EventArgs e)
        {
            if (Environment.OSVersion.Platform != PlatformID.WinCE)
                return;

            HideKeypad();
            this.Text = m_Keypad.EnteredText;
            if (m_eNumericEntered != null)
                m_eNumericEntered(sender, e);            
        }

        public event EventHandler OnEntered
        {
            add { m_eNumericEntered += value; }
            remove { m_eNumericEntered -= value; }
        }

        public event EventHandler OnCanceled
        {
            add { m_eNumericCanceled += value; }
            remove { m_eNumericCanceled -= value; }
        }
    }
}
