package org.jerrymouse.cc.site.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jerrymouse.cc.site.bean.Resource;
import org.jerrymouse.cc.site.bean.Storage;
import org.jerrymouse.cc.site.bean.Type;
import org.jerrymouse.cc.site.bean.User;
import org.jerrymouse.cc.site.convert.CommonConvertor;
import org.jerrymouse.cc.site.database.UserDao;
import org.jerrymouse.cc.site.web.result.PutResourceResult;
import org.jerrymouse.cc.site.web.utils.CCRequestContext;
import org.jerrymouse.cc.utils.ResourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Path("{username}/storage")
public class StorageWeb {
	@Autowired
	private UserDao userDao;

	private Storage storage;

	@GET
	@Produces(MediaType.TEXT_HTML)
	public Response list(@PathParam("username") String username) {
		// error check
		if (userDao.getUserByName(username) == null) {
			return Response.status(404).build();
		}
		// list
		storage = userDao.getUserByName(username).getStorage();
		List<Resource> resources = storage.getResources();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", username);
		map.put("resources", resources);
		String text = ResourceBuilder.getResourcesBuilder().vm("dictionary.vm",
				map);
		return Response.ok(text).build();
	}

	@SuppressWarnings("unchecked")
	@POST
	@Consumes( { "multipart/form-data" })
	@Produces(MediaType.TEXT_HTML)
	public Response putResource(@PathParam("username") String username,
			byte[] data, @Context HttpHeaders httpHeaders) {
		User user = userDao.getUserByName(username);
		if (user == null) {
			return jsonToTxt(new PutResourceResult(false)).build();
		}
		storage = user.getStorage();
		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());
		byte[] bytes = null;
		String orgFilename = null;
		try {
			List<FileItem> list = upload.parseRequest(new CCRequestContext(
					data, httpHeaders));
			for (FileItem item : list) {
				if (!item.isFormField()) {
					bytes = item.get();
					orgFilename = item.getName();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		if (bytes == null || bytes.length == 0) {
			return jsonToTxt(new PutResourceResult(false)).build();
		}
		Resource resource = new Resource(user, orgFilename);
		storage.addResource(resource);
		resource.putBytes(bytes);
		userDao.put(user);
		List<Type> ts = new CommonConvertor().support().get(
				resource.getOrgType());

		return jsonToTxt(
				new PutResourceResult(resource.getOrgFullFilename(), resource
						.getOrgType(), ts)).build();
	}

	private ResponseBuilder jsonToTxt(Object object) {
		return Response.ok(JSONObject.fromObject(object).toString(),
				MediaType.TEXT_PLAIN);
	}
}
