/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.util;

import java.io.IOException;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * Class to get a tiny URL from a longer URL.
 * @author buckett
 */
public class TinyUrl
{
    
    public static final String URL = "http://tinyurl.com/api-create.php";
    public static final String VERSION = "Java TinyURL 0.1";
    
    private static final Pattern pattern = Pattern.compile("http://tinyurl.com/\\w+");
    
    private String error;

    /**
     * Attempts to shortern a URL
     * @param url The URL to shortern.
     * @return The tiny URL or null if it failed.
     */
    public String shorten(String url)
    {
        String result = null;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(URL);
        NameValuePair[] data = {
            new NameValuePair("url", url),
            new NameValuePair("source", VERSION)
          };
        method.setRequestBody(data);
        try
        {
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK)
            {
                String response = method.getResponseBodyAsString();
                if ((response.indexOf("Error") == -1))        
                {
                    if (pattern.matcher(response).matches())
                    {
                        result = response;
                    }
                    else
                    {
                        error = "Response didn't match a valid tiny url.";
                    }
                }
                else
                {
                    error = "Got error back.";
                }
            }
            else
            {
                error = "Bad HTTP code: "+ method.getStatusCode();
            }
        }
        catch (IOException ioe)
        {
            error = "IO Problem connecting to "+ URL+ " "+ ioe.getMessage();
        }
        return result;
    }
    
    /**
     * @return Returns the last error we encountered.
     */
    public String getError()
    {
        return error;
    }

}
