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


namespace Bellmonzo.Koubai.Common.Windows.Validate
{
    public class FormValidator
    {
        static private Color errorBackColor = Color.Red;
        static private Color normalBackColor = Color.White;
        static public void ErrorClear(Control owner)
        {
            if (owner.BackColor == errorBackColor)
            {
                owner.BackColor = normalBackColor;
            }
            foreach (Control c in owner.Controls)
            {
                ErrorClear(c);
            }
        }

        static public void SetError(String message, Control control)
        {
            control.BackColor = errorBackColor;
            control.Focus();
            throw new ValidateException(message);
        }

        static public void RequiredCheck(string itemName, Control control)
        {
            var text = control.Text;
            if (text == String.Empty)
            {
                SetError(String.Format("{0}を入力してください", itemName), control);
            }
        }

        /// <summary>
        /// 数値の入力範囲
        /// </summary>
        /// <param name="itemName"></param>
        /// <param name="control"></param>
        /// <param name="startRange"></param>
        /// <param name="endRange"></param>
        /// <returns></returns>
        static public int InRangeCheck(String itemName, Control control, int startRange, int endRange)
        {
            RequiredCheck(itemName, control);

            var text = control.Text;
            int num;
        
            if (Int32.TryParse(text,out num) == false ){
                SetError(String.Format("{0}は数字で入力してください。", itemName), control);
            }
            if (!(startRange <= num && num <= endRange)) {
                SetError(String.Format("{0}は{1}～{2}の範囲で指定してください。", itemName, startRange, endRange), control);
            }
             return num;
       }
    }
}
