package se.l4.dust.jaxrs.internal.asset;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import se.l4.dust.api.asset.Asset;
import se.l4.dust.api.resource.Resource;

import com.google.inject.Inject;
import com.google.inject.Stage;

/**
 * {@link MessageBodyWriter} for {@link Asset}.
 * 
 * @author Andreas Holstenson
 */
@Provider
@Produces("*/*")
public class AssetWriter
	implements MessageBodyWriter<Asset>
{
	private final String date;
	private final boolean development;
	private final long maxAge;
	
	@Inject
	public AssetWriter(Stage stage)
	{
		development = stage == Stage.DEVELOPMENT;
		
		long time = System.currentTimeMillis();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, 1);
		c.add(Calendar.DAY_OF_MONTH, -1);
		
		date = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(c.getTime());
		maxAge = c.getTimeInMillis() - time;
	}
	
	public long getSize(Asset t, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType)
	{
		Resource resource = t.getResource();
		return resource.getContentLength();
	}

	public boolean isWriteable(Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType)
	{
		return Asset.class.isAssignableFrom(type);
	}

	public void writeTo(Asset t, Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, Object> httpHeaders,
			OutputStream entityStream)
		throws IOException, WebApplicationException
	{
		Resource resource = t.getResource();
		
		if(false == development)
		{
			httpHeaders.putSingle("Cache-Control", "public, max-age=" + maxAge);
			httpHeaders.putSingle("Expires", date);
		}
		
		String contentType = getMimeType(t);
		httpHeaders.putSingle("Last-Modified", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date(resource.getLastModified())));
		
		if(contentType != null)
		{
			httpHeaders.putSingle("Content-Type", contentType);
			
			if(contentType.startsWith("text/"))
			{
				httpHeaders.putSingle("Vary", "Accept-Encoding");
			}
		}
		
		InputStream stream = null;
		try
		{
			stream = resource.openStream();
			
			byte[] buffer = new byte[1024];
			int l;
			while((l = stream.read(buffer)) != -1)
			{
				entityStream.write(buffer, 0, l);
			}
		}
		finally
		{
			if(stream != null)
			{
				stream.close();
			}
		}
	}

	public static String getMimeType(Asset asset)
	{
		String contentType = asset.getResource().getContentType();
		if(contentType == null || "".equals(contentType) || "content/unknown".equals(contentType) || "unknown".equals(contentType))
		{
			contentType = getLazyMimeType(asset);
		}
		
		return contentType;
	}
	
	private static String getLazyMimeType(Asset asset)
	{
		String name = asset.getName();
		if(name.endsWith(".css"))
		{
			return "text/css";
		}
		else if(name.endsWith(".js"))
		{
			return "text/javascript";
		}
		else
		{
			return "application/octet-stream";
		}
	}
}

@@ -342,32 +342,69 @@
 ationException;%0A
+import javax.ws.rs.core.HttpHeaders;%0A
 import javax.ws.
@@ -866,36 +866,8 @@
 %3E%0A%7B%0A
-%09private final String date;%0A
 %09pri
@@ -1171,92 +1171,8 @@
 %0A%09%09%0A
-%09%09date = new SimpleDateFormat(%22EEE, dd MMM yyyy HH:mm:ss zzz%22).format(c.getTime());%0A
 %09%09ma
@@ -1985,22 +1985,109 @@
 le(%22
-Expires%22, date
+Date%22, new Date());%0A%09%09%09httpHeaders.putSingle(%22Expires%22, new Date(System.currentTimeMillis() + maxAge)
 );%0A%09
@@ -2180,69 +2180,8 @@
 new 
-SimpleDateFormat(%22EEE, dd MMM yyyy HH:mm:ss zzz%22).format(new 
 Date
@@ -2209,17 +2209,16 @@
 fied()))
-)
 ;%0A%09%09%0A%09%09i
@@ -2303,115 +2303,8 @@
 e);%0A
-%09%09%09%0A%09%09%09if(contentType.startsWith(%22text/%22))%0A%09%09%09%7B%0A%09%09%09%09httpHeaders.putSingle(%22Vary%22, %22Accept-Encoding%22);%0A%09%09%09%7D%0A
 %09%09%7D%0A

Include Date header for assets