package cn.base.servlet;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.util.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.net.www.protocol.ftp.FtpURLConnection;
import cn.base.bean.BeanHelper;
import cn.base.util.ImageHepler;
import cn.base.util.StringUtil;

@SuppressWarnings("serial")
public class CutZoomImageServlet extends HttpServlet{
	
	private static Log log = LogFactory.getLog(CutZoomImageServlet.class);

	public void doPost(HttpServletRequest request, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		String tempUrl = null;
		try {
			Integer viewPortW = Integer.parseInt(request.getParameter("viewPortW"));
			Integer viewPortH = Integer.parseInt(request.getParameter("viewPortH"));
			Integer imageX = Integer.parseInt(request.getParameter("imageX"));
			Integer imageY = Integer.parseInt(request.getParameter("imageY"));
			Integer imageRotate = Integer.parseInt(request.getParameter("imageRotate"));
			Integer imageW = Integer.parseInt(request.getParameter("imageW"));
			Integer imageH = Integer.parseInt(request.getParameter("imageH"));
			Integer selectorX = Integer.parseInt(request.getParameter("selectorX"));
			Integer selectorY = Integer.parseInt(request.getParameter("selectorY"));
			Integer selectorW = Integer.parseInt(request.getParameter("selectorW"));
			Integer selectorH = Integer.parseInt(request.getParameter("selectorH"));
			String imageZoom = request.getParameter("zoom");
			String imageSource = request.getParameter("imageSource");
			
			boolean ishttp = imageSource.indexOf("HTTP://")==0 || imageSource.indexOf("http://")==0 ;
			boolean isftp  = imageSource.indexOf("FTP://")==0 || imageSource.indexOf("ftp://")==0 ;
			URL url = null;
			DataInputStream in = null;
			if(ishttp){
				url = new URL(imageSource);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				in = new DataInputStream(connection.getInputStream());
				imageSource = Base64.encodeBase64String(IOUtils.toByteArray(in));
			}else if(isftp){
				url = new URL(imageSource);
				FtpURLConnection connection = (FtpURLConnection) url.openConnection();
				in = new DataInputStream(connection.getInputStream());
				imageSource = Base64.encodeBase64String( IOUtils.toByteArray(in));
			} else{
				imageSource = imageSource.split(",")[1];
			}
			
	//		System.out.println("viewPortW==="+viewPortW);
	//		System.out.println("viewPortH==="+viewPortH);
	//		System.out.println("imageX==="+imageX);
	//		System.out.println("imageY==="+imageY);
	//		System.out.println("imageRotate==="+imageRotate);
	//		System.out.println("imageW==="+imageW);
	//		System.out.println("imageH==="+imageH);
	//		System.out.println("selectorX==="+selectorX);
	//		System.out.println("selectorY==="+selectorY);
	//		System.out.println("selectorW==="+selectorW);
	//		System.out.println("selectorH==="+selectorH);
	//		System.out.println("zoom==="+imageZoom);
	//		System.out.println("imageSource==="+imageSource);
			int cutTop = selectorY - imageY;
			cutTop = cutTop<0?0:cutTop;
			int cutLeft = selectorX - imageX;
			cutLeft = cutLeft<0?0:cutLeft;
			int dropWidth = selectorW;
			int dropHeight = selectorH;
			BufferedImage img = base642BufferedImage(imageSource,imageW,imageH);
			Rectangle rec = new Rectangle(cutLeft, cutTop, dropWidth, dropHeight);
			String tUrl = BeanHelper.getModuleConfFactory().getScatter().getPcfg();
			if(tUrl.startsWith("/")){ //linux with absolute path
				tUrl = tUrl.split("/")[1];
			}else{ //windows
				tUrl = tUrl.split(":")[0];
			}
			tUrl = tUrl+File.separator+"vp"+File.separator+"uploadpath"+File.separator+"cutImg";
			File  ff  = new File(tUrl);
			if(!ff.exists()){
				ff.mkdirs();
			}
			tempUrl =tUrl+File.separator+StringUtil.getUUID()+".png";
			File file = new File(tempUrl);
			String sFile = imageSource;
			if(imageZoom.equals("true")){//可缩放
	//			ImageHepler.saveSubImage(img,file, imageWidth, imageHeight, rec);
				saveSubImage(img, file, img.getWidth(), img.getHeight(), rec);
			} else if(imageZoom.equals("false")){//无缩放
				Image image = ImageIO.read(new File(sFile));
				float zoomRate = 0;
				if( imageW == viewPortW){
					zoomRate = (float)(image.getWidth(null))/(float)(imageW);
				} else if(imageH == viewPortH){
					zoomRate = (float)(image.getHeight(null))/(float)(imageH);
				}
				rec = new Rectangle((int)(cutLeft*zoomRate), (int)(cutTop*zoomRate), (int)(dropWidth*zoomRate), (int)(dropHeight*zoomRate));
				saveSubImage(new File(sFile), file, image.getWidth(null), image.getHeight(null), rec);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("CutZoomImageServlet-dopost error:" + e);
		}
		String base64Url = (tempUrl ==null) ? null: ImgUrl2Base64(tempUrl);
		PrintWriter out = null;
		try {
			out = response.getWriter();
		}catch (Exception e) {
			e.printStackTrace();
			log.error("CutZoomImageServlet-dopost getWriter error:" + e);
		}
        out.print(base64Url);  
        out.flush();
        out.close();
		return;
	}

	private static void saveSubImage(File srcImageFile, File descDir, int width, int height, Rectangle rect) throws IOException {
		ImageHepler.cut(srcImageFile, descDir, width, height, rect);
	}
	private static void saveSubImage(BufferedImage img, File descDir, int width, int height, Rectangle rect) throws IOException {
		ImageHepler.cut(img, descDir, width, height, rect);
	}
	 public static void delAllFile(String path) {
		File file = new File(path);
		if (!file.isDirectory()) {
			file.mkdirs();
		}
		String[] tempList = file.list();
		File temp = null;
		if (tempList!=null&&tempList.length > 4) {
			for (int i = 0; i <tempList.length; i++) {
				if (path.endsWith(File.separator)) {
					temp = new File(path + tempList[i]);
				} else {
					temp = new File(path + File.separator + tempList[i]);
				}
				if (temp.isFile()) {
					temp.delete();
					break;
				}
				if (temp.isDirectory()) {
					delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				}
			}
		}
	}
	 public BufferedImage base642BufferedImage(String base64Str,int width,int height){
		 BufferedImage image = null;
		 if (base64Str == null) //图像数据为空  
	            return null;  
	        BASE64Decoder decoder = new BASE64Decoder();  
	        try   
	        {  
	            //Base64解码  
	            byte[] b = decoder.decodeBuffer(base64Str);  
	            for(int i=0;i<b.length;++i)  
	            {  
	                if(b[i]<0)  
	                {//调整异常数据  
	                    b[i]+=256;  
	                }  
	            }  
	            ByteArrayInputStream in = new ByteArrayInputStream(b);
	            image = ImageIO.read(in);
	            image = ImageHepler.makeThumbnail(image,width,height);
	        }catch (Exception e)   
	        {  
	            return null;  
	        }  
	        return image;
	 }
	 public static String ImgUrl2Base64(String imgFile)  
	    {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理  
	        InputStream in = null;  
	        byte[] data = null;  
	        //读取图片字节数组  
	        try   
	        {  
	            in = new FileInputStream(imgFile);          
	            data = new byte[in.available()];  
	            in.read(data);  
	            in.close();  
	        }   
	        catch (IOException e)   
	        {  
	            e.printStackTrace();  
	        }  
	        //对字节数组Base64编码  
	        BASE64Encoder encoder = new BASE64Encoder();  
	        return encoder.encode(data);//返回Base64编码过的字节数组字符串  
	    } 
}
