package org.orienteer.core.resource;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.tika.Tika;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.AbstractResource;
import org.apache.wicket.request.resource.IResource;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.request.resource.SharedResourceReference;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.time.Time;
import org.orienteer.core.MountPath;
import org.orienteer.core.OrienteerWebApplication;

import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.impl.ODocument;

/**
 * Share dynamic resources such as image, video and other.
 */
@MountPath("/content/${rid}/${field}")
public class OContentShareResource extends AbstractResource {
    
    public static SharedResourceReference getSharedResourceReference() {
    	return new SharedResourceReference(OContentShareResource.class.getName());
    }
    
    public static CharSequence urlFor(ODocument document, String field, String contentType, boolean fullUrl) {
    	return urlFor(getSharedResourceReference(), document, field, contentType, fullUrl);
    }

    protected static CharSequence urlFor(ResourceReference ref, ODocument document, String field, String contentType, boolean fullUrl) {
    	PageParameters params = new PageParameters();
    	params.add("rid", document.getIdentity().toString().substring(1));
    	params.add("field", field);
    	params.add("v", document.getVersion());
    	if(!Strings.isEmpty(contentType)) params.add("type", contentType);
    	CharSequence url = RequestCycle.get().urlFor(ref, params);
    	if(fullUrl) {
    		url = RequestCycle.get().getUrlRenderer().renderFullUrl(Url.parse(url));
    	}
    	return url;
    }

    @Override
    protected ResourceResponse newResourceResponse(IResource.Attributes attributes) {
        final ResourceResponse response = new ResourceResponse();
        response.setLastModified(Time.now());
        if (response.dataNeedsToBeWritten(attributes)) {
            PageParameters params = attributes.getParameters();
            String rid = "#"+params.get("rid").toOptionalString();
            ODocument document = ORecordId.isA(rid) ? new ORecordId(rid).getRecord() : null;
            if (document != null) {
                String field = params.get("field").toString();
                final byte [] data = getContent(document, field);
                if (data != null && data.length > 0) {
                    String contentType = params.get("type").toOptionalString();
                	if (Strings.isEmpty(contentType)) {
                		contentType = new Tika().detect(data);
                	}
                    response.setContentType(contentType);
                    response.setWriteCallback(createWriteCallback(data));
                }
            }

            if (response.getWriteCallback() == null) {
                response.setError(HttpServletResponse.SC_NOT_FOUND);
            }

        }
        return response;
    }
    
    protected byte[] getContent(ODocument doc, String field) {
    	if(doc==null) return null;
    	return doc.field(field, byte[].class);
    }

    private WriteCallback createWriteCallback(byte [] data) {
        return new WriteCallback() {
            @Override
            public void writeData(IResource.Attributes attributes) throws IOException {
                attributes.getResponse().write(data);
            }
        };
    }
}

@@ -707,24 +707,74 @@
 plication;%0A%0A
+import com.orientechnologies.orient.core.id.ORID;%0A
 import com.o
@@ -2383,16 +2383,19 @@
 ring rid
+Str
  = %22#%22+p
@@ -2444,33 +2444,24 @@
        O
-Document document
+RID orid
  = OReco
@@ -2472,16 +2472,19 @@
 .isA(rid
+Str
 ) ? new 
@@ -2500,20 +2500,11 @@
 (rid
-).getRecord(
+Str
 ) : 
@@ -2525,24 +2525,20 @@
     if (
-document
+orid
  != null
@@ -2652,24 +2652,20 @@
 Content(
-document
+orid
 , field)
@@ -3313,28 +3313,23 @@
 ontent(O
-Document doc
+RID rid
 , String
@@ -3334,24 +3334,62 @@
 ng field) %7B%0A
+    %09ODocument doc = rid.getRecord();%0A
     %09if(doc=

Allow getContent() in OContentShareResource recieve ORID instead doc