using System;
using System.Drawing;
using System.Windows.Forms;

namespace CLIP.eForm.Consent.UI
{
    public partial class SignaturePasswordForm : Form
    {
        //선언
        private CLIP.eForm.UI.Parts.VirtualKeyboard.VirtualKeyboardForm _virKeyForm = null; //가상키보드

        private bool dualViewerState = false;

        public SignaturePasswordForm(string userName, string userId, bool dualViewer)
        {
            InitializeComponent();

            this.Text = string.Format("{0} - {1}", userName, userId);
            dualViewerState = dualViewer;

            // 이벤트 연결
            this.textBoxPassword.Click += new EventHandler(control_Click);
        }

        /// <summary>
        /// textBoxPassword 입력 컨트롤 클릭 이벤트 연결
        /// 듀얼 뷰어 상태가 아닐때 가상 키보드를 보여준다
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void control_Click(object sender, EventArgs e)
        {
            if (!dualViewerState)
            {
                ShowVirtualKeyboard(CLIP.eForm.UI.Parts.VirtualKeyboard.KeyboardType.CharKeyboard);
                Control control = sender as Control;
                control.Focus();
            }
        }

        /// <summary>
        /// 확인 버튼 클릭 이벤트
        /// 가상키보드를 숨기고 창을 닫는다
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textBoxPassword.Text))
            {
                HideVirtualKeyboard();
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        /// <summary>
        /// 사용자가 입력한 패스워드 반환
        /// </summary>
        /// <returns>인증서 비밀번호 반환</returns>
        public string GetPassword()
        {
            return this.textBoxPassword.Text.ToString();
        }

        /// <summary>
        /// textBoxPassword 텍스트 박스 컨트롤 키보드 입력 이벤트
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyPressEventArgs"/> instance containing the event data.</param>
        private void textBoxPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 엔터키 입력 시 가상키보드를 숨기고 창을 닫는다
            if (e.KeyChar == (char)Keys.Return)
            {
                if (!string.IsNullOrEmpty(this.textBoxPassword.Text))
                {
                    HideVirtualKeyboard();
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
        }

        /// <summary>
        /// 가상키보드 보이기
        /// </summary>
        /// <param name="keyboardType">키보드 타입</param>
        private void ShowVirtualKeyboard(CLIP.eForm.UI.Parts.VirtualKeyboard.KeyboardType keyboardType)
        {
            HideVirtualKeyboard();
            if (_virKeyForm == null)
            {
                _virKeyForm = new CLIP.eForm.UI.Parts.VirtualKeyboard.VirtualKeyboardForm(CLIP.eForm.UI.Parts.VirtualKeyboard.IME.korean, keyboardType, true);
                _virKeyForm.OnKeyPressEvent += new KeyEventHandler(_virKeyForm_OnKeyPressEvent); //Key-Down Event
                _virKeyForm.OnClickCustomExitButton += new EventHandler(_virKeyForm_OnClickCustomExitButton); //가상키보드 종료이벤트
                _virKeyForm.StartPosition = FormStartPosition.Manual;
            }
            //Set Location
            _virKeyForm.Bounds = GetVirtualKeyboardLocation(keyboardType);
            _virKeyForm.Show();
        }

        /// <summary>
        /// Key-Down 이벤트 연결 주로
        /// 특정키의 입력에 대해 처리하는경우, 사용한다.
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Key Info</param>
        private void _virKeyForm_OnKeyPressEvent(object sender, KeyEventArgs e)
        {
            //// 사용예제
            //if (e.KeyData == Keys.Enter || e.KeyData == Keys.Escape)
            //{
            //    //특정로직 처리
            //    HideVirtualKeyboard();
            //}
        }

        /// <summary>
        /// 가상키보드 위치잡기
        /// 프로그램이 위치한 스크린 하단의 Location을 반환한다.
        /// </summary>
        /// <param name="keyboardType">키보드 타입</param>
        /// <returns></returns>
        private Rectangle GetVirtualKeyboardLocation(CLIP.eForm.UI.Parts.VirtualKeyboard.KeyboardType keyboardType)
        {
            int x = 0;
            int bottom = 0;
            int width = 0;
            int minusTitleBarHeight = SystemInformation.ToolWindowCaptionHeight + SystemInformation.FrameBorderSize.Height;
            Rectangle screenLocation = GetScreenPosition();
            if (keyboardType == CLIP.eForm.UI.Parts.VirtualKeyboard.KeyboardType.CharKeyboard)
            {
                x = screenLocation.X;
                width = screenLocation.Width;
            }
            else if (keyboardType == CLIP.eForm.UI.Parts.VirtualKeyboard.KeyboardType.NumPad)
            {
                x = screenLocation.X + screenLocation.Width - _virKeyForm.Width;
                width = (int)(screenLocation.Width / 3.0f);
            }
            bottom = screenLocation.Height - _virKeyForm.Height - minusTitleBarHeight;
            return new Rectangle(x, bottom, width, _virKeyForm.Height);
        }
        /// <summary>
        /// 현재 프로그램이 위치한 스크린의 Bound정보를 반환한다.
        /// </summary>
        /// <returns></returns>
        private Rectangle GetScreenPosition()
        {
            Screen[] dualScreen = Screen.AllScreens;
            Rectangle screenBound = Rectangle.Empty;
            foreach (Screen sc in dualScreen)
            {
                if (sc.Bounds.Contains(this.Location) == true)
                {
                    screenBound = sc.WorkingArea;
                    break;
                }
            }
            return screenBound;
        }

        //가상키보드 숨기기
        private void HideVirtualKeyboard()
        {
            if (_virKeyForm != null)
            {
                _virKeyForm.Close();
                _virKeyForm = null;
            }
        }

        //가상키보드 종료버튼 함수
        private void _virKeyForm_OnClickCustomExitButton(object sender, EventArgs e)
        {
            HideVirtualKeyboard();
        }

        private void SignaturePasswordForm_Load(object sender, EventArgs e)
        {
            if(!dualViewerState)
            {
                ShowVirtualKeyboard(CLIP.eForm.UI.Parts.VirtualKeyboard.KeyboardType.CharKeyboard);
                this.textBoxPassword.Focus();
            }
        }

        protected override void OnActivated(EventArgs e)
        {
            this.textBoxPassword.Focus();
            base.OnActivated(e);
        }

        private void SignaturePasswordForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            HideVirtualKeyboard();
        }

        private void tabpointButton1_Click(object sender, EventArgs e)
        {
            HideVirtualKeyboard();
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
}
