using System.Net;
using System.Net.Cache;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace ynhtm.API
{
    using Common;

    public class Domain : BaseHandler
    {
        static Encoding ENCODING = Encoding.GetEncoding("GB2312");

        public override void Process()
        {
            var request = this.Request;
            var response = this.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.Cache.SetNoStore();
            var xml = this.OutputXml;
            var key = request["q"];
            xml.WriteStartDocument();
            xml.WriteStartElement("domain");
            xml.WriteElementString("key", key);
            xml.WriteElementString("status", RegStatus(key));
            xml.WriteEndElement();
            xml.WriteEndDocument();
            xml.Close();
            response.End();
        }

        public static string RegStatus(string key)
        {
            var request = (HttpWebRequest)WebRequest.Create("http://panda.www.net.cn/cgi-bin/check.cgi?area_domain=" + HttpUtility.UrlEncode(key, Encoding.GetEncoding("GB2312")));
            request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            request.Method = "GET";
            using (var stream = request.GetResponse().GetResponseStream())
            {
                var xml = XElement.Load(stream);
                if (xml.Element("returncode").Value == "200") return xml.Element("original").Value.Substring(0, 3);
            }
            return "212";
        }
    }
}