package com.devflow.util;

import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.devflow.models.Album;

/**
 * Class: contains methods for parsing an Imgur URL string
 * 
 */
public class ImgurParser
{
    /**
     * Parse an Imgur album URL and returns an Album object
     * 
     * @param url
     * @return
     */
    public static Album ParseAlbumURL(String url)
    {
        // 2) First fetch the HTML text
    	StringBuilder html = new StringBuilder(1024);
        try
        {
        	URL page = new URL(url);
        	char[] buffer = new char[1024 * 1024];
        	InputStreamReader is = new InputStreamReader(page.openStream());
        	int amt;
        	while((amt = is.read(buffer)) != -1)
        	{
        		html.append(buffer, 0, amt);
        	}
        	is.close();
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        	return new Album("", "", 0, new LinkedList<String>());
        }

        // 3) If fetch is successful, parse the page and return the new album object
        Album album = ImgurParser.ParseAlbum(html.toString(), url);

        return album;
    }

    /**
     * Helper method that does the real work to parse the html and json, and returns the album java
     * object
     * 
     * @param doc
     * @param albumURL
     * @return
     * @throws JSONException
     */
    private static Album ParseAlbum(String docString, String albumURL) throws JSONException
    {
        //System.out.println(docString.length());
        String jsonBeginString = "Imgur.Album.getInstance(";

        // Marks the beginning of the JSON object
        int beginIndex = docString.indexOf(jsonBeginString);

        // Add it to the index so we only get the JSON string
        docString = docString.substring(beginIndex + jsonBeginString.length());

        // Marks the end of the JSON object
        int endIndex = docString.indexOf(");");

        // Use 0 as begin index b/c we already shortened the string
        docString = docString.substring(0, endIndex);

        /** Begin parsing our JSON album object **/
        //System.out.println(beginIndex + " " + endIndex);
        JSONObject albumObject = new JSONObject(docString);

        String title = albumObject.getJSONObject("album").optString("title", null);
        JSONObject imagesObject = albumObject.getJSONObject("images");

        int imageCount = imagesObject.getInt("count");

        JSONArray imageArray = imagesObject.getJSONArray("items");

        List<String> filenameArray = new ArrayList<String>();

        for (int i = 0; i < imageArray.length(); i++)
        {
            String hash = imageArray.getJSONObject(i).getString("hash");
            String ext = imageArray.getJSONObject(i).getString("ext");

            // Take out the question mark that might be part of the extension
            if (ext.contains("?"))
                ext = ext.substring(0, ext.indexOf('?'));
            
            // "ext" already contains a period in front; no need to add one manually
            filenameArray.add(hash + ext);  
        }

        return new Album(albumURL, title, imageCount, filenameArray);
    }
}