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.jx.jyhd.simcpux.Util;
import com.jx.jyhd.simcpux.Wxistrue;
import com.nickming.view.listener.savelistener;

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.io.InputStream;
import java.security.InvalidParameterException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import fi.iki.elonen.NanoHTTPD;

public class OkHttpPhotoServer extends NanoHTTPD {
    
    private static savelistener listener1;
    public static Handler handler;
    private static String bitmappath;
    private ExecutorService executor;
    
    public OkHttpPhotoServer(int port) {
        super(port);
        executor = Executors.newFixedThreadPool(4);
    }
    
    public static void setPhotoListener(savelistener listener) {
        listener1 = listener;
    }
    
    public static void setPhotoHandler(Handler hanler1) {
        handler = hanler1;
    }
      @Override
    public Response serve(IHTTPSession session) {
        String uri = session.getUri();
        
        // 只处理 /testurl 路径的请求
        if (!"/testurl".equals(uri)) {
            return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "Not Found");
        }
        
//        if (!Wxistrue.isphotoshare) { // 避免重复点击
            System.out.println("8888888888");
            if (Method.POST.equals(session.getMethod())) {
                if (handler != null) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Wxistrue.isphotoshare = true;
                        }
                    }, 3000);
                }
                
                Wxistrue.isphotoshare = false;                try {
                    // 简化POST数据读取
                    String postData = readPostData(session);
                    
                    System.out.println(postData);
                    
                    String photo = "";
                    String type = "";
                    
                    try {
                        // 尝试解析JSON格式
                        JSONObject object = new JSONObject(postData);
                        photo = object.optString("name");
                        
                        // 从原始数据中提取type
                        if (postData.contains("data")) {
                            int dataIndex = postData.indexOf("data");
                            if (dataIndex > 0) {
                                type = postData.substring(dataIndex - 1, dataIndex);
                            }
                        }
                        
                        //photo = deleteHeader(photo);
                        System.out.println("json格式");
                    } catch (JSONException e) {
                        //photo = deleteHeader(postData);
                        System.out.println("不是json格式");
                        e.printStackTrace();
                    }
                    
                    //saveBase64(photo);
                    Message msg = new Message();
                    
                    Bundle data = new Bundle();
                    data.putString("bitmap", photo);
                    data.putString("bitpath", bitmappath);
                    data.putString("type", type);
                    System.out.println(type);
                    msg.setData(data);
                    
                    if (handler != null) {
                        handler.sendMessage(msg);
                    }
                    
                } catch (Exception e) {
                    e.printStackTrace();
                    return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, "text/plain", "服务器错误");
                }
                
            } else if (Method.GET.equals(session.getMethod())) {
                // 处理GET请求参数
                Map<String, String> params = session.getParms();
                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());
            }
            
            return newFixedLengthResponse(Response.Status.OK, "text/plain; charset=utf-8", "请求成功。");
//        }
//
//        return newFixedLengthResponse(Response.Status.TOO_MANY_REQUESTS, "text/plain", "请求过于频繁");
    }
      private String getPostDataFromStream(IHTTPSession session) {
        try {
            Map<String, String> headers = session.getHeaders();
            String contentLength = headers.get("content-length");
            if (contentLength != null) {
                int length = Integer.parseInt(contentLength);
                if (length > 0) {
                    byte[] buffer = new byte[length];
                    InputStream inputStream = session.getInputStream();
                    int totalRead = 0;
                    while (totalRead < length) {
                        int read = inputStream.read(buffer, totalRead, length - totalRead);
                        if (read <= 0) break;
                        totalRead += read;
                    }
                    return new String(buffer, 0, totalRead, "UTF-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    // 提供一个更简单的POST数据读取方法
    private String readPostData(IHTTPSession session) {
        try {
            Map<String, String> parms = session.getParms();
            // 如果是表单提交，参数会在parms中
            if (!parms.isEmpty()) {
                // 如果有name参数，直接返回
                if (parms.containsKey("name")) {
                    return parms.get("name");
                }
                // 否则返回第一个参数的值
                return parms.values().iterator().next();
            }
            
            // 如果不是表单提交，尝试读取原始POST数据
            return getPostDataFromStream(session);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    
    private String deleteHeader(String photo) {
        int start = photo.indexOf(",");
        if (start != -1) {
            photo = photo.substring(start + 1);
        }
        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("图片为空");
        }
        getScreenShot(bit1, bitmappath);
    }
    
    private void getScreenShot(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();
    }
}
