// Chattr - Twitter client on .NET
//
// Copyright (c) 2007,2008,2009,2010 Katsuhiko Ichinose <ichi@users.sourceforge.jp>
//
// Chattr is Free Software released under GNU General Public License.
//
// $Id: BitlyAPI.cs 234 2010-01-31 11:59:04Z ichi $

using System;
using System.Collections.Generic;
using System.Text;

using System.Text.RegularExpressions;
using System.Net;
using System.Net.NetworkInformation;
using System.Web;
using System.Xml;

using System.Diagnostics;

namespace Chattr
{
    static class BitlyAPI
    {
        private const string API = "api.bit.ly";
        private const string VERSION = "2.0.1";

        static public string CreateShorten(string url, string login, string apiKey)
        {
            string result = null;
            string req = "http://" + API + "/shorten?version=" + VERSION +
                            "&longUrl=" + UrlEncode(url, "[?&\\+]") +
                            "&login=" + login +
                            "&apiKey=" + apiKey +
                            "&format=xml";
            HttpWebResponse res = Get(req);
            if (res != null)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    XmlDocument xml = new XmlDocument();
                    try
                    {
                        xml.Load(res.GetResponseStream());
                        if (xml.ChildNodes.Count > 0)
                        {
                            XmlNode node = xml.FirstChild;
                            if (node.Name == "bitly")
                            {
                                if (node["statusCode"].InnerText == "OK")
                                {
                                    result = node["results"]["nodeKeyVal"]["shortUrl"].InnerText;
                                    Debug.WriteLine("BitlyAPI.CreateShorten(): " + result);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("BitlyAPI.CreateShorten() Error\n" +
                            ex.Message + "\n" + "Source: " + ex.Source);
                    }
                }
                res.Close();
            }
            return result;
        }

        static private string UrlEncode(string text, string encode)
        {
            Debug.WriteLine("Bitly.UrlEncode: " + text);
            string txt = text;
            string msg = "";
            Regex r = new Regex("^(.*?)(" + encode + "+)(.*)$");
            Match m = r.Match(txt);
            while (m.Success)
            {
                msg += m.Groups[1].Value;
                foreach (byte a in Encoding.ASCII.GetBytes(m.Groups[2].Value))
                {
                    msg += string.Format("%{0:x2}", a);
                }
                txt = m.Groups[3].Value;
                m = r.Match(txt);
            }
            msg += txt;
            Debug.WriteLine("BitlyAPI.UrlEncode: " + msg);
            return msg;
        }

        static private void SetProxy(HttpWebRequest req)
        {
            if (Properties.Settings.Default.UseProxy == FormMain.PROXY_CHATTR)
            {
                req.Proxy = FormMain.GetProxy();
            }
        }

        static public HttpWebResponse Get(String url)
        {
            Debug.WriteLine("BitlyAPI.Get: " + url);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            req.KeepAlive = false;
            req.CookieContainer = null;
            req.Timeout = 5000;
            SetProxy(req);
            HttpWebResponse res = null;
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    res = (HttpWebResponse)req.GetResponse();
                }
                else
                {
                    throw new WebException("Is not network available.", WebExceptionStatus.ConnectFailure);
                }
            }
            catch (SystemException ex)
            {
                Debug.WriteLine("Twitter.Get(\'" + url + "\') Error\n" +
                    ex.Message + "\n" + "Source: " + ex.Source);
                if (ex.GetType() == typeof(WebException))
                {
                    Debug.WriteLine("Status: " + ((WebException)ex).Status);
                }
            }
            return res;
        }
    }
}
