using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using TABS.MailCarrier.AuxLib;
using TABS.MailCarrier.WebSDK;

/// <summary>
/// Web.config에 정의된 appSettings 값을 참조한다.
/// </summary>
public class AppSetting
{
    // 메일
    static int _fileboxLinkValidHour = 72;
    static long _maxMailAttachSize = 20 * 1024 * 1024;
    static long _sizeOfChangeToDownloadLink = 15 * 1024 * 1024;
    static List<RcptAutoCompleteSourceType> _rcptAutoCmplSources = new List<RcptAutoCompleteSourceType>();
    static int _rcptAutoCompleteCacheTimeMin = 10;
    static bool _useSenderInfo = true;
    static bool _useDefaultSenderInfo = true;
    static bool _supportParseTNEF = false;
    static bool _enableReadReceipt = true;
    static bool _displayMailSummary = false;
    static string _mailSearchCategory = "subject";
    static bool _supportBcc = true;
    static bool _enableSpamReport = true;

    // 전자결재
    static bool _useApproval = true;
    static int _apvCollaboration = 1;
    static int _applyApprovalType = 2;
    static string _newApprovalNotificationTemplateFile = "";
    static string _applyApprovalNotificationTemplateFile = "";
    static string _rejectApprovalNotificationTemplateFile = "";
    static string _suspendApprovalNotificationTemplateFile = "";
    static bool _apvSuspendedStatus = false;

    // 조직도
    static bool _orgzListPartFirst = true;

    // 게시판
    static bool _useBoard = true;
    static string _newArticleNotificationTemplateFile = "";
    static string _boardCommentTemplateFile = "";
    static long _maxBoardAttachSize = 1 * 1024 * 1024 * 1024;
    static string _one2oneQuestionTemplateFile = "";
    static string _one2oneAnswerTemplateFile = "";
    static bool _useBoardCommentLineBreak = false;

    // 바이러스 검사
    static bool _enableVirusCheck = true;
    static long _limitVirusCheckSize = 10485760;

    // 웹에디터
    static string _editorDefaultFont = "Malgun Gothic";
    static string _editorDefaultFontSize = "10pt";
    static string _editorDefaultLineHeight = "normal";

    // 일정
    static bool _useCalendar = true;
    static bool _showAppCreationTime = false;

    // 파일함
    static bool _useFilebox = true;

    // 디자인
    static bool _useCustomTitle = false;
    static bool _supportDarkMode = false;
    static string _cssVersion = "";

    // SSO
    static bool _enableSsoUsingReferer = false;
    static bool _enableSsoUsingSecureToken = false;
    static string _singleSignOnPassword = "";

    // 기타
    static bool _encodingFileName = true;
    static bool _useFulltextSearch = false;
    static bool _controlLoginSeparately = false;
    static bool _useEncryptPassword = false;
    static bool _useTimeZone = false;
    static bool _useOTP = true;
    static bool _forceUseOfOTP = false;
    static string _otpFreeZone = "";
    // OTPFreeZone 검사에 사용되는 IpFilter
    static IpFilter2 _ipFilter4OtpFreeZone = null;
    static bool _redirectHttps = false;
    static string _useBrowserConfirm = "true";
    static bool _allowMobileDeviceOnly = false;
    static string _webAppVersion = "7.5.5.";
    static bool _supportWebPush = true;
    static bool _useSafeAddress4Download = false;
    static bool _useDisplayBoardFilter = false;
    static int _imageCacheMaxAgeMin = 30 * 24 * 60;     // 30일
    static bool _useLogWriter = false;

    public enum RcptAutoCompleteSourceType : int
    {
        RecentUsed = 1,                           // 최근 발송한 메일 주소
        DomainUsers = 2,                          // 동일 도메인 사용자
        UserContacts = 3,                         // 개인 주소록
        SharedContacts = 4,                       // 공유 주소록
        Organization = 5,                         // 조직도(외부 메일 주소 제외)
        ExternalMailAddrs = 6,                    // 조직도 외부 메일 주소
        AllowDuplicate = 7,                       // 중복 허용(데이터 소스는 아니고 플래그)
        AllowSort = 8                             // 정렬 여부(데이터 소스는 아니고 플래그)
    }

    #region Custom UI for each Domain

    /// <summary>
    /// 도메인에 대한 타이틀 및 메인 이미지 정보를 저장
    /// </summary>
    public class TitleInfo
    {
        public TitleInfo()
        {
            _title = "WebMobile";
            _authDomain = "";
            _acceptIpFilter = new IpFilter2("1.1.1.1/0.0.0.0");      // 모든 IP 대역을 허락
        }

        public TitleInfo(string title, string authDomain, string acceptIp)
        {
            _title = title;
            _authDomain = authDomain;
            if (_title == "") _title = "WebMobile";
            if (acceptIp == "") acceptIp = "1.1.1.1/0.0.0.0";
            _acceptIpFilter = new IpFilter2(acceptIp);
        }

        public string Title
        {
            get { return _title; }
        }

        public string AuthDomain
        {
            get { return _authDomain; }
        }

        public void Add(string name, string value)
        {
            _nvCollection.Add(name, value);
        }

        public string this[string name] 
        {
            get
            {
                try
                {
                    return _nvCollection[name];
                }
                catch (KeyNotFoundException)
                {
                    return "";
                }
            }
        }

        public bool IsAcceptedIP(string ip)
        {
            if (ip == "::1") ip = "127.0.0.1";
            return !_acceptIpFilter.Pass(ip);
        }

        private string _title;
        private string _authDomain;
        private Dictionary<string, string> _nvCollection = new Dictionary<string, string>();
        private IpFilter2 _acceptIpFilter = null;
    }

    /// <summary>
    /// TitleInfo를 저장하는 맵
    /// </summary>
    private class DomainInfoMap : Dictionary<string, TitleInfo>
    {
        public DomainInfoMap(string xmlFile)
        {
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.Load(xmlFile);
                foreach (XmlNode itemNode in xml.DocumentElement.ChildNodes)
                {
                    string host = "", title = "", authdomain = "", acceptip = "";
                    Dictionary<string, string> collection = new Dictionary<string, string>();
                    foreach (XmlNode childNode in itemNode.ChildNodes)
                    {
                        bool apply = true;
                        if (childNode.Attributes != null)
                        {
                            XmlAttribute applyAttr = childNode.Attributes["apply"];
                            if (applyAttr != null && applyAttr.Value == "false") apply = false;
                        }
                        if (apply)
                        {
                            switch (childNode.Name)
                            {
                                case "host": host = childNode.InnerText.Trim(); break;
                                case "title": title = childNode.InnerText.Trim(); break;
                                case "authdomain": authdomain = childNode.InnerText.Trim(); break;
                                case "acceptip": acceptip = childNode.InnerText.Trim(); break;
                                default:
                                    collection.Add(childNode.Name, childNode.InnerText.Trim());
                                    break;
                            }
                        }
                    }
                    if (host.Length > 0)
                    {
                        TitleInfo titleInfo = new TitleInfo(title, authdomain, acceptip);
                        foreach (KeyValuePair<string, string> pair in collection)
                        {
                            titleInfo.Add(pair.Key, pair.Value);
                        }
                        this[host.ToLower()] = titleInfo;
                    }
                }
            }
            catch
            {
            }
        }
    }

    #endregion

    static object _thisLock = new object();

    public AppSetting()
    {
    }

    /// <summary>
    /// Web.config에 정의된 appSettings 값을 읽는다.
    ///  - Global.asax의 Application_Start()에서 1회 호출한다. 
    /// </summary>
    public static void Load()
    {
        // 메일
        GetValue("FileboxLinkValidHour", ref _fileboxLinkValidHour);
        GetSizeValue("MaxMailAttachSize", ref _maxMailAttachSize);
        GetSizeValue("SizeOfChangeToDownloadLink", ref _sizeOfChangeToDownloadLink);
        GetValue("RcptAutoCompleteSource", ref _rcptAutoCmplSources);
        GetValue("RcptAutoCompleteCacheTimeMin", ref _rcptAutoCompleteCacheTimeMin);
        GetValue("UseSenderInfo", ref _useSenderInfo);
        GetValue("UseDefaultSenderInfo", ref _useDefaultSenderInfo);
        GetValue("SupportParseTNEF", ref _supportParseTNEF);
        GetValue("EnableReadReceipt", ref _enableReadReceipt);
        GetValue("DisplayMailSummary", ref _displayMailSummary);
        GetValue("MailSearchCategory", ref _mailSearchCategory);
        if (!(new string[] { "subject", "body", "sender", "receiver", "all" }.Any(s => _mailSearchCategory.Equals(s)))) _mailSearchCategory = "subject";
        GetValue("SupportBcc", ref _supportBcc);
        GetValue("EnableSpamReport", ref _enableSpamReport);

        // 전자결재
        GetValue("UseApproval", ref _useApproval);
        GetValue("ApvCollaborationType", ref _apvCollaboration);
        GetValue("ApplyApprovalType", ref _applyApprovalType);
        _newApprovalNotificationTemplateFile = GetTemplateFileFullPath(GetValue("NewApprovalNotificationTemplateFile"));
        _applyApprovalNotificationTemplateFile = GetTemplateFileFullPath(GetValue("ApplyApprovalNotificationTemplateFile"));
        _rejectApprovalNotificationTemplateFile = GetTemplateFileFullPath(GetValue("RejectApprovalNotificationTemplateFile"));
        _suspendApprovalNotificationTemplateFile = GetTemplateFileFullPath(GetValue("SuspendApprovalNotificationTemplateFile"));
        GetValue("ApvSuspendedStatus", ref _apvSuspendedStatus);

        // 조직도
        GetValue("OrgzListPartFirst", ref _orgzListPartFirst);

        // 게시판
        GetValue("UseBoard", ref _useBoard);
        _newArticleNotificationTemplateFile = GetTemplateFileFullPath(GetValue("NewArticleNotificationTemplateFile"));
        _boardCommentTemplateFile = GetTemplateFileFullPath(GetValue("BoardCommentTemplateFile"));
        GetSizeValue("MaxBoardAttachSize", ref _maxBoardAttachSize);
        _one2oneQuestionTemplateFile = GetTemplateFileFullPath(GetValue("One2oneQuestionTemplateFile"));
        _one2oneAnswerTemplateFile = GetTemplateFileFullPath(GetValue("One2oneAnswerTemplateFile"));
        GetValue("UseBoardCommentLineBreak", ref _useBoardCommentLineBreak);

        // 일정
        GetValue("UseCalendar", ref _useCalendar);
        GetValue("ShowAppCreationTime", ref _showAppCreationTime);

        // 파일함
        GetValue("UseFilebox", ref _useFilebox);

        // 바이러스 검사
        GetValue("EnableVirusCheck", ref _enableVirusCheck);
        GetSizeValue("LimitVirusCheckSize", ref _limitVirusCheckSize);

        // 웹에디터
        GetValue("EditorDefaultFont", ref _editorDefaultFont);
        if (_editorDefaultFont == "") _editorDefaultFont = "Malgun Gothic";
        GetLowerValue("EditorDefaultFontSize", ref _editorDefaultFontSize);
        if (_editorDefaultFontSize == "") _editorDefaultFontSize = "10pt";
        GetLowerValue("EditorDefaultLineHeight", ref _editorDefaultLineHeight);
        if (_editorDefaultLineHeight == "") _editorDefaultLineHeight = "normal";

        // 디자인
        string cssVersion = "";
        GetValue("UseCustomTitle", ref _useCustomTitle);
        GetValue("SupportDarkMode", ref _supportDarkMode);
        GetValue("CssVersion", ref cssVersion);
        _cssVersion = (cssVersion != "") ? "?v=" + cssVersion : "";

        // SSO
        GetValue("EnableSsoUsingReferer", ref _enableSsoUsingReferer);
        GetValue("EnableSsoUsingSecureToken", ref _enableSsoUsingSecureToken);
        GetValue("SingleSignOnPassword", ref _singleSignOnPassword);

        // 기타        
        GetValue("EncodingFileName", ref _encodingFileName);
        
        GetValue("UseFulltextSearch", ref _useFulltextSearch);
        GetValue("ControlLoginSeparately", ref _controlLoginSeparately);
        GetValue("UseEncryptPassword", ref _useEncryptPassword);
        GetValue("UseTimeZone", ref _useTimeZone);
        GetValue("UseOTP", ref _useOTP);
        GetValue("ForceUseOfOTP", ref _forceUseOfOTP);
        GetValue("OTPFreeZone", ref _otpFreeZone);
        GetValue("RedirectHttps", ref _redirectHttps);
        GetValue("UseBrowserConfirm", ref _useBrowserConfirm);
        GetValue("AllowMobileDeviceOnly", ref _allowMobileDeviceOnly);
        GetValue("SupportWebPush", ref _supportWebPush);
        GetValue("UseSafeAddress4Download", ref _useSafeAddress4Download);
        GetValue("UseDisplayBoardFilter", ref _useDisplayBoardFilter);
        GetValue("ImageCacheMaxAgeMin", ref _imageCacheMaxAgeMin);
        GetValue("UseLogWriter", ref _useLogWriter);
        GetValue("WebAppVersion", ref _webAppVersion);

        _ipFilter4OtpFreeZone = new IpFilter2(_otpFreeZone);
    }

    /// <summary>
    /// 파일 다운로드시 비영문 파일 이름 인코딩 여부
    /// </summary>
    public static bool EncodingFileName
    {
        get { return _encodingFileName; }
    }

    /// <summary>
    /// 새글, 답글 작성시 메일 발송을 위한 발송폼 경로를 지정
    /// </summary>
    public static string NewArticleNotificationTemplateFile
    {
        get { return _newArticleNotificationTemplateFile; }
    }

    /// <summary>
    /// 댓글 작성 시 메일 발송을 위한 발송폼 파일을 지정
    /// </summary>
    public static string BoardCommentTemplateFile
    {
        get { return _boardCommentTemplateFile; }
    }

    public static string One2oneQuestionTemplateFile
    {
        get { return _one2oneQuestionTemplateFile; }
    }

    public static string One2oneAnswerTemplateFile
    {
        get { return _one2oneAnswerTemplateFile; }
    }

    /// <summary>
    /// 메일에 포함된 파일함 파일 다운로드 경로가 유효한 시간
    /// </summary>
    public static int FileboxLinkValidHour
    {
        get { return _fileboxLinkValidHour; }
    }

    public static string NewApprovalNotificationTemplateFile
    {
        get { return _newApprovalNotificationTemplateFile; }
    }

    public static int ApplyApprovalType
    {
        get { return _applyApprovalType; }
    }

    public static string ApplyApprovalNotificationTemplateFile
    {
        get { return _applyApprovalNotificationTemplateFile; }
    }

    public static string RejectApprovalNotificationTemplateFile
    {
        get { return _rejectApprovalNotificationTemplateFile; }
    }

    public static string SuspendApprovalNotificationTemplateFile
    {
        get { return _suspendApprovalNotificationTemplateFile; }
    }

    public static int ApvCollaboration
    {
        get { return _apvCollaboration; }
    }

    public static bool UseApproval
    {
        get { return _useApproval; }
    }

    public static bool ApvSuspendedStatus
    {
        get { return _apvSuspendedStatus; }
    }
    public static bool EnableVirusCheck
    {
        get { return _enableVirusCheck; }
    }

    public static long LimitVirusCheckSize
    {
        get { return _limitVirusCheckSize; }
    }

    public static bool UseFulltextSearch
    {
        get { return _useFulltextSearch; }
    }

    public static long MaxMailAttachSize
    {
        get { return _maxMailAttachSize; }
    }

    public static long SizeOfChangeToDownloadLink
    {
        get { return _sizeOfChangeToDownloadLink; }
    }

    public static bool ControlLoginSeparately
    {
        get { return _controlLoginSeparately; }
    }

    public static bool UseEncryptPassword
    {
        get { return _useEncryptPassword; }
    }

    public static bool UseBoard
    {
        get { return _useBoard; }
    }

    public static bool UseCalendar
    {
        get { return _useCalendar; }
    }

    public static bool ShowAppCreationTime
    {
        get { return _showAppCreationTime; }
    }

    public static bool UseFilebox
    {
        get { return _useFilebox; }
    }

    public static List<RcptAutoCompleteSourceType> RcptAutoCompleteSources
    {
        get { return _rcptAutoCmplSources; }
    }

    public static int RcptAutoCompleteCacheTimeMin
    {
        get { return _rcptAutoCompleteCacheTimeMin; }
    }

    public static long MaxBoardAttachSize
    {
        get { return _maxBoardAttachSize; }
    }

    public static bool UseTimeZone
    {
        get { return GlobalConfig.SchemaVersion >= 730 && _useTimeZone; }
    }

    public static bool UseSenderInfo
    {
        get { return _useSenderInfo; }
    }

    public static bool UseDefaultSenderInfo
    {
        get { return _useDefaultSenderInfo; }
    }

    public static bool SupportParseTNEF
    {
        get { return _supportParseTNEF; }
    }

    public static bool UseOTP
    {
        get { return GlobalConfig.SchemaVersion >= 730 && _useOTP; }
    }

    public static bool ForceUseOfOTP
    {
        get { return _forceUseOfOTP; }
    }

    public static bool EnableSsoUsingReferer
    {
        get { return _enableSsoUsingReferer; }
    }

    public static bool EnableSsoUsingSecureToken
    {
        get { return _enableSsoUsingSecureToken; }
    }

    public static string SingleSignOnPassword
    {
        get { return _singleSignOnPassword; }
    }

    public static bool OrgzListPartFirst
    {
        get { return _orgzListPartFirst; }
    }

    public static bool SupportDarkMode
    {
        get { return _supportDarkMode; }
    }

    public static string CssVer
    {
        get { return _cssVersion; }
    }

    public static bool DisplayMailSummary
    {
        get { return _displayMailSummary; }
    }

    public static string MailSearchCategory
    {
        get { return _mailSearchCategory; }
    }

    public static bool EnableReadReceipt
    {
        get { return _enableReadReceipt; }
    }

    public static bool SupportBcc
    {
        get { return _supportBcc; }
    }

    public static bool EnableSpamReport
    {
        get { return _enableSpamReport; }
    }

    public static bool RedirectHttps
    {
        get { return _redirectHttps; }
    }

    public static string UseBrowserConfirm
    {
        get { return _useBrowserConfirm; }
    }

    public static bool UseBoardCommentLineBreak
    {
        get { return _useBoardCommentLineBreak; }
    }

    public static string WebAppVersion
    {
        get { return _webAppVersion; }
    }

    public static string EditorDefaultFont
    {
        get { return _editorDefaultFont; }
    }

    public static string EditorDefaultFontSize
    {
        get { return _editorDefaultFontSize; }
    }

    public static string EditorDefaultLineHeight
    {
        get { return _editorDefaultLineHeight; }
    }

    public static bool AllowMobileDeviceOnly
    {
        get { return _allowMobileDeviceOnly; }
    }

    public static bool SupportWebPush
    {
        get { return _supportWebPush; }
    }

    public static bool UseSafeAddress4Download
    {
        get { return _useSafeAddress4Download; }
    }

    public static bool UseLogWriter
    {
        get { return _useLogWriter; }
    }

    public static bool IsSafeAddress()
    {
        bool retval = true;
        if (_useSafeAddress4Download)
        {
            WebMobile.Extend.SafeAddress safeAddr = new WebMobile.Extend.SafeAddress();
            retval = safeAddr.IsSafe(HttpContext.Current, WebUser.CurrentUser.MailAddress);
        }
        return retval;
    }

    public static bool PassDisplayBoardFilter(Guid boardId, string userEmail)
    {
        bool retval = true;
        if (_useDisplayBoardFilter)
        {
            WebMobile.Extend.DisplayBoardFilter filter = new WebMobile.Extend.DisplayBoardFilter();
            retval = filter.Pass(HttpContext.Current, boardId, WebUser.CurrentUser.MailAddress);
        }
        return retval;
    }

    public static bool PassDisplayBoardFilter(string userEmail)
    {
        bool retval = true;
        if (_useDisplayBoardFilter)
        {
            WebMobile.Extend.DisplayBoardFilter filter = new WebMobile.Extend.DisplayBoardFilter();
            retval = filter.PassAdmin(HttpContext.Current, WebUser.CurrentUser.MailAddress);
        }
        return retval;
    }


    public static int ImageCacheMaxAgeMin
    {
        get { return _imageCacheMaxAgeMin; }
    }

    /// <summary>
    /// 도메인에 따른 타이틀 정보를 반환한다.
    /// </summary>
    /// <param name="host">웹 페이지 ULR 중 호스트 이름</param>
    /// <returns></returns>
    public static TitleInfo GetTitleInfo(string host)
    {
        if (!_useCustomTitle) return new TitleInfo();

        const string cacheKey = "GlobalTitleInfo";
        HttpContext context = HttpContext.Current;
        DomainInfoMap domainInfoMap = (DomainInfoMap)context.Cache[cacheKey];

        if (domainInfoMap == null)
        {
            lock (_thisLock)
            {
                domainInfoMap = (DomainInfoMap)context.Cache[cacheKey];
                if (domainInfoMap == null)
                {
                    string appDataPath = HttpContext.Current.Server.MapPath("~/app_data");
                    string xmlFile = string.Format("{0}\\MainTitle.xml", appDataPath);
                    domainInfoMap = new DomainInfoMap(xmlFile);
                    context.Cache.Insert(cacheKey, domainInfoMap, new CacheDependency(xmlFile));
                }
            }
        }

        TitleInfo titleInfo = null;
        if (domainInfoMap.TryGetValue(host.ToLower(), out titleInfo))
        {
            return titleInfo;
        }
        else
        {
            return new TitleInfo();
        }
    }

    /// <summary>
    /// 도메인에 따른 타이틀 정보를 반환한다.
    /// </summary>
    /// <param name="request">웹 요청</param>
    /// <returns></returns>
    public static TitleInfo GetTitleInfo(HttpRequest request)
    {
        return GetTitleInfo(request.Headers["Host"]);
    }

    public static bool ExistInOtpFreeZone(string ip)
    {
        return _ipFilter4OtpFreeZone.Pass(ip) == false;
    }

    #region GetValue variantions

    public static string GetAppSettingValue(string key, string defaultValue)
    {
        string value = defaultValue;
        try
        {
            if (ConfigurationManager.AppSettings[key] != null) value = ConfigurationManager.AppSettings[key];
        }
        catch (ConfigurationErrorsException)
        {
            value = defaultValue;
        }
        return value;
    }

    public static bool GetAppSettingValue(string key, bool defaultValue)
    {
        string value = GetAppSettingValue(key, defaultValue ? "true" : "false");
        return value == "true";
    }

    private static string GetValue(string key)
    {
        try
        {
            return (ConfigurationManager.AppSettings[key] != null) ? ConfigurationManager.AppSettings[key] : "";
        }
        catch (ConfigurationErrorsException)
        {
        }
        return "";
    }

    private static void GetValue(string key, ref string value)
    {
        try
        {
            if (ConfigurationManager.AppSettings[key] != null) value = ConfigurationManager.AppSettings[key];
        }
        catch (ConfigurationErrorsException)
        {
        }
    }

    private static void GetLowerValue(string key, ref string value)
    {
        try
        {
            if (ConfigurationManager.AppSettings[key] != null)
            {
                value = ConfigurationManager.AppSettings[key].ToLower();
            }
        }
        catch (ConfigurationErrorsException)
        {
        }
    }

    private static void GetValue(string key, ref long value)
    {
        try
        {
            if (ConfigurationManager.AppSettings[key] != null) value = long.Parse(ConfigurationManager.AppSettings[key]);
        }
        catch (ConfigurationErrorsException)
        {
        }
    }

    private static void GetSizeValue(string key, ref long value)
    {
        try
        {
            if (ConfigurationManager.AppSettings[key] != null)
            {
                string strval = ConfigurationManager.AppSettings[key].ToString();
                string size_p = @"^(?<size>(\d+))(?<unit>(kb|mb|gb)*)$";
                Regex r = new Regex(size_p, RegexOptions.IgnoreCase);
                Match m = r.Match(strval);
                if (m.Success)
                {
                    long unit = 1;
                    string strUnit = m.Groups["unit"].ToString().ToUpper();
                    if (strUnit == "GB") unit = 1024 * 1024 * 1024;
                    else if (strUnit == "MB") unit = 1024 * 1024;
                    else if (strUnit == "KB") unit = 1024;
                    value = long.Parse(m.Groups["size"].ToString()) * unit;
                }
            }
        }
        catch (ConfigurationErrorsException)
        {
        }
    }

    private static void GetValue(string key, ref int value)
    {
        try
        {
            if (ConfigurationManager.AppSettings[key] != null) value = int.Parse(ConfigurationManager.AppSettings[key]);
        }
        catch (ConfigurationErrorsException)
        {
        }
    }

    private static void GetValue(string key, ref bool value)
    {
        try
        {
            if (ConfigurationManager.AppSettings[key] != null) value = (ConfigurationManager.AppSettings[key].ToLower() == "true");
        }
        catch (ConfigurationErrorsException)
        {
        }
    }

    private static void GetValue(string key, ref List<RcptAutoCompleteSourceType> value)
    {
        value.Clear();
        string strValue = "";
        GetValue("RcptAutoCompleteSource", ref strValue);
        string[] strFlags = strValue.Split(',');
        foreach (string strFlag in strFlags)
        {
            switch (strFlag.Trim().ToLower())
            {
                case "recentused":
                    value.Add(RcptAutoCompleteSourceType.RecentUsed);
                    break;
                case "domainusers":
                    value.Add(RcptAutoCompleteSourceType.DomainUsers);
                    break;
                case "usercontacts":
                    value.Add(RcptAutoCompleteSourceType.UserContacts);
                    break;
                case "sharedcontacts":
                    value.Add(RcptAutoCompleteSourceType.SharedContacts);
                    break;
                case "organization":
                    value.Add(RcptAutoCompleteSourceType.Organization);
                    break;
                case "externalmailaddrs":
                    value.Add(RcptAutoCompleteSourceType.ExternalMailAddrs);
                    break;
                case "allowduplicate":
                    value.Add(RcptAutoCompleteSourceType.AllowDuplicate);
                    break;
                case "allowsort":
                    value.Add(RcptAutoCompleteSourceType.AllowSort);
                    break;
            }
        }
    }

    #endregion

    private static String GetTemplateFileFullPath(string fileName)
    {
        if (fileName.Length < 3) return fileName;
        if (fileName[1] == ':' && fileName[2] == '\\') return fileName;

        string templatePath = HttpContext.Current.Server.MapPath("~/Template");
        return string.Format("{0}\\{1}", templatePath, fileName);
    }

}