using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;

namespace URLShortener
{
    class clsURLShort
    {
        List<string> providerList;
        string apiKey;

        public clsURLShort(string apiKey)
        {
            this.apiKey = apiKey;
            this.providerList = new List<string>();
            this.getProviderList();
        }

        public string createURLShort(string url, int count)
        {
            string urlList = string.Empty;

            for (int i = 0; i < count; i++)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://tiny-url.info/api/v1/create?apikey=" + apiKey + "&format=json&provider=" + providerList[i] + "&url=" + Uri.EscapeDataString(url) + "&callback=?");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    StreamReader readStream = new StreamReader(stream);
                    string result = readStream.ReadToEnd();

                    if (result.IndexOf("\"ok\"") > -1) urlList += Regex.Split(result, "shorturl\":\"(.*?)\"")[1] + "\r\n";
                }
            }
            return urlList;
        }

        private void getProviderList()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://tiny-url.info/open_api.html");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream stream = response.GetResponseStream();
                StreamReader readStream = new StreamReader(stream);
                string result = readStream.ReadToEnd();
                string[] splitArr = Regex.Split(result, "<td align=\"center\" bgcolor=\"#FFFFFF\">(.*?)</td>");

                for (int i = 1; i < splitArr.Length; i += 2) providerList.Add(splitArr[i]);
            }
        }
    }
}