import java.io.*;
import java.net.*;
import java.util.*;

import org.codehaus.jackson.map.ObjectMapper;


/**
 * This class gets listings from Etsy's web service API.
 */
public class EtsyListingFetcher {

	private static String API_KEY = "foo"; // PUT YOUR ETSY API KEY HERE
	private static String URL_START = "https://openapi.etsy.com/v2/listings/active?api_key=" + API_KEY + "&page=1&limit=100&fields=title,description,category_path,price,url&includes=MainImage";

	static class Listing {
		String url;
		String title;
		String description;
		String price;
		String imageUrl;
		List<String> categories;

		public Listing(String url, String title, String description, String price, String imageUrl, List<String> categories) {
			this.url = url;
			this.title = title;
			this.description = description;
			this.price = price;
			this.imageUrl = imageUrl;
			this.categories = categories;
		}

		public String toString() {
			return title + " " + categories + " $" + price;
		}
	}


	public static List<Listing> fetchListings(String query) throws IOException {
		List<Listing> list = new ArrayList<Listing>();

		InputStream inputStream = null;
		try {
			String queryEscaped = URLEncoder.encode(query, "UTF-8");
			String webServiceUrl = URL_START + "&keywords=" + queryEscaped;
			inputStream = (new URL(webServiceUrl)).openStream();

			ObjectMapper objMapper = new ObjectMapper();
			Map<String, Object> map = objMapper.readValue(inputStream, Map.class);

			List<Map<String, Object>> results = (List<Map<String, Object>>) map.get("results");
			for (Map<String, Object> result : results) {
				Listing listing = parseListing(result);
				if (listing != null) {
					list.add(listing);
				}
			}
		} finally {
			inputStream.close();
		}

		return list;
	}

	private static Listing parseListing(Map<String, Object> result) {
		String url = (String) result.get("url");
		String title = (String) result.get("title");
		String description = (String) result.get("description");
		String price = (String) result.get("price");

		Map imgData = (Map) result.get("MainImage");
		String imageUrl = (imgData != null) ? ((String) imgData.get("url_170x135")) : null;

		List categories = (List) result.get("category_path");

		return new Listing(url, title, description, price, imageUrl, categories);
	}

	public static void main(String args[]) throws IOException {
		List<Listing> list = fetchListings("hat");
		for (Listing listing : list) {
			System.out.println(listing);
		}
	}
}