using System;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Net.Security;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CookComputing.XmlRpc;

namespace BTS.Trac
{
    /// <summary>
    /// XML-RPC ベースクラス
    /// </summary>
    /// <typeparam name="T">XML-RPC インタフェース</typeparam>
    public class TracXmlRpcBase<T> where T : class, IXmlRpcProxy
    {
        /// <summary>
        /// XML-RPC インタフェース
        /// </summary>
        public T Content
        {
            get;
            private set;
        }

        /// <summary>
        /// URL
        /// </summary>
        public string Url
        {
            get;
            private set;
        }

        /// <summary>
        /// ユーザー名
        /// </summary>
        public string UserName
        {
            get;
            private set;
        }

        /// <summary>
        /// パスワード
        /// </summary>
        public string Password
        {
            get;
            private set;
        }

        /// <summary>
        /// XML-RPC インタフェースの作成
        /// </summary>
        /// <param name="url"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public void Create( string url, string userName, string password )
        {
            Url = url;
            UserName = userName;
            Password = password;

            // see http://trac-hacks.org/wiki/DotNet
            ServicePointManager.ServerCertificateValidationCallback = AcceptCertificateNoMatterWhat;

            // インスタンスの生成
            Content = XmlRpcProxyGen.Create( typeof( T ) ) as T;
            Content.Url = url;
            Content.PreAuthenticate = true;
            Content.KeepAlive = false;
            Content.Credentials = new NetworkCredential( userName, password );
        }

        /// <summary>
        /// Trac I/F の終了
        /// </summary>
        public void Close()
        {
            Url = "";
            UserName = "";
            Password = "";

            Content = null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="cert"></param>
        /// <param name="chain"></param>
        /// <param name="errors"></param>
        /// <returns>true</returns>
        /// <note>http://trac-hacks.org/wiki/DotNet</note>
        private bool AcceptCertificateNoMatterWhat( object sender, X509Certificate cert,
                                                    X509Chain chain, SslPolicyErrors errors )
        {
            return true;
        }
    }
}
