package com.x.customUpload.assemble.control.jaxrs.sample;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.config.StorageMapping;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoFile;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.customUpload.assemble.control.ThisApplication;
import com.x.customUpload.core.entity.UploadEntity;

public class ActionDownloadStream extends BaseAction {
	
	private static  Logger logger = LoggerFactory.getLogger( ActionDownloadStream.class );
	
	protected ActionResult<Wo> execute( HttpServletRequest request, EffectivePerson effectivePerson, String id, Boolean stream ) throws Exception {
		ActionResult<Wo> result = new ActionResult<>();
		UploadEntity attachment = null;
		Boolean check = true;
		Wo wo = null;
		try {
			attachment = attachmentQueryService.get( id );
			if( attachment == null ){
				check = false;
				Exception exception = new ExceptionAttachmentNotExists( id );
				result.error( exception );
			}
		} catch ( Exception e ) {
			check = false;
			Exception exception = new ExceptionAttachmentQueryById( e, id );
			result.error( exception );
			logger.error( e, effectivePerson, request, null);
		}
		
		if( Boolean.TRUE.equals( check ) ){
			StorageMapping mapping = ThisApplication.context().storageMappings().get(UploadEntity.class, attachment.getStorage());
			wo = new Wo(attachment.readContent(mapping), 
					this.contentType(stream, attachment.getName()), 
					this.contentDisposition(stream, attachment.getName()));
		}

		result.setData(wo);
		return result;
	}

	public static class Wo extends WoFile {
		
		@FieldDescribe("操作引起的动态内容")
		List<WoDynamic> dynamics = new ArrayList<>();

		public List<WoDynamic> getDynamics() {
			return dynamics;
		}

		public void setDynamics(List<WoDynamic> dynamics) {
			this.dynamics = dynamics;
		}
		
		public Wo(byte[] bytes, String contentType, String contentDisposition) {
			super(bytes, contentType, contentDisposition);
		}
	}

	public static class WoDynamic extends UploadEntity{

		private static final long serialVersionUID = -5076990764713538973L;

		public static WrapCopier<UploadEntity, WoDynamic> copier = WrapCopierFactory.wo( UploadEntity.class, WoDynamic.class, null, JpaObject.FieldsInvisible);
		
		private Long rank = 0L;

		public Long getRank() {
			return rank;
		}

		public void setRank(Long rank) {
			this.rank = rank;
		}		
	}
	
}
