package com.tagmae.tsgame_erwang;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;

import com.nickming.view.listener.savelistener;
import com.jx.jyhd.simcpux.Util;
import com.jx.jyhd.simcpux.Wxistrue;
import com.yanzhenjie.andserver.AndServerRequestHandler;
import com.yanzhenjie.andserver.util.HttpRequestParser;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.Map;

public class AndServerTestHandle implements AndServerRequestHandler {
	
	
	private static savelistener listener1;
	
	public  static Handler hanler;
	
	private static String bitmappath;
	public static void setPhotoListerer(savelistener listener){
		listener1=listener;
	}
	
	
	public static void setPhotohandler(Handler hanler1){
		hanler=hanler1;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void handle(HttpRequest request, HttpResponse response, HttpContext arg2)
			throws HttpException, IOException {

		if(Wxistrue.isphotoshare){//避免重复点击
			System.out.println("8888888888");
			if(HttpRequestParser.isPosterMethod(request)){
				if(hanler!=null){
					hanler.postDelayed(new Runnable() {
						@Override
						public void run() {
							Wxistrue.isphotoshare=true;
							Wxistrue.isphotoshare=true;
						}
					},3000);
				}

				Wxistrue.isphotoshare=false;
				
				String name=HttpRequestParser.getContentForPost(request);
				
				System.out.println(name);
				String photo="";
				
				String type=name.substring(name.indexOf("data")-1, name.indexOf("data"));


				//type="3";

		        System.out.println(type);
		       
			    try {
					JSONObject object=new JSONObject(name);
					 photo=object.optString("name");
					 
					 
					 photo=deleteheard(photo);
					System.out.println("json格式");
				} catch (JSONException e) {
					 photo=deleteheard(name);
					System.out.println("不是json格式");
					e.printStackTrace();
				}
				saveBase64(photo);
				Message msg=new Message();
				
				
				
				//listener1.save(bitmappath);
				
				Bundle data=new Bundle();
				data.putString("bitpath", bitmappath);
				data.putString("type", type);
                System.out.println(type);
				msg.setData(data);
				hanler.sendMessage(msg);
				

				
				}else{
					// 拿到客户端参数key-value。
			        Map<String, String> params = HttpRequestParser.parse(request);
			        StringBuilder stringBuilder = new StringBuilder();
			        for (Map.Entry<String, String> entry : params.entrySet()) {
			        	System.out.println(entry.getKey() + ": " + entry.getValue());
			            stringBuilder.append(entry.getKey() + ": " + entry.getValue() + "\r\n");
			        }
			        
			        System.out.println("客户端提交的参数：" + stringBuilder.toString());
				}
				
				response.setEntity(new StringEntity("请求成功。", "utf-8"));
		}
		
		
	}
	private String deleteheard(String photo) {
		int start=photo.indexOf(",");
		photo=photo.substring(start+1, photo.length());
		System.out.println(photo);
		return photo;
	}
	
	public void saveBase64(String iconBase64){
		File file;
		
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// sd卡存储（/mnt/sdcard/cache）
			file = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			// 没有SD卡，缓存到系统存储
			file = Environment.getDataDirectory();
		}
		file = Util.GetDirectory();
		bitmappath = file.getAbsolutePath() + File.separator + "photo.png";
		Bitmap bit1=stringtoBitmap(iconBase64);
		if(bit1==null){
			System.out.println("图片为空");
		}
		getScreenHot(bit1,bitmappath);
		
		
		
	}

private void getScreenHot(Bitmap b1,String filePath) {
	System.out.println(filePath);
	if(b1==null){
		System.out.println("-----");
	}
	File file1 = new File(filePath);
	try {
		file1.createNewFile();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	try {
		try {
			
			FileOutputStream fos = new FileOutputStream(file1);
			b1.compress(CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			throw new InvalidParameterException();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}

	
	 public Bitmap stringtoBitmap(String string) {  
	        // 将字符串转换成Bitmap类型  
	        Bitmap bitmap = null;  
	        try {  
	                byte[] bitmapArray;  
	                System.out.println(string);
	                bitmapArray = Base64.decode(string, Base64.DEFAULT); 
	                bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,  
	                                bitmapArray.length); 
	                
	        } catch (Exception e) {  
	                e.printStackTrace();  
	        }  
	        return bitmap;  

	}  
	 public String bitmaptoString(Bitmap bitmap) {  
	        // 将Bitmap转换成字符串  
	        String string = null;  
	        ByteArrayOutputStream bStream = new ByteArrayOutputStream();  
	        bitmap.compress(CompressFormat.PNG, 100, bStream);  
	        byte[] bytes = bStream.toByteArray();  
	        string = Base64.encodeToString(bytes, Base64.DEFAULT);  
	        return string;  
	}
	 
	 
	 interface savePhotoListener{
			void success();
	 }
}
