package com.reactnative.drwine;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import Decoder.BASE64Encoder;

/**
 * Created by YinMenglong on 2017/3/16.
 */

public class ImageToBase64Module extends ReactContextBaseJavaModule {

    public ImageToBase64Module(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "DRImageToBase64";
    }

    @ReactMethod
    public void getBase64String(final String uri, final Callback callback) {
        if (TextUtils.isEmpty(uri)) {
            callback.invoke("uri undefined", null);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String imageBase64 = doownPhoto(uri);
                    callback.invoke("success", imageBase64);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Base64", "报错了");
                    callback.invoke("err", null);
                }
            }
        }).start();

    }

    /**
     * 下载图片
     *
     * @param uri 图片url
     */
    private String doownPhoto(String uri) throws Exception {

        URL url = new URL(uri);
        String type = this.getPhotoType(url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();

        if (inStream == null) {
            return null;
        }

        BASE64Encoder encoder = new BASE64Encoder();
        String str = encoder.encode(this.readStream(inStream));//返回Base64编码过的字节数组字符串;
        str = "data:" + type + ";base64," + str;
        return str;

    }

    private String getPhotoType(URL url) {

        try {
            HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
            urlconnection.connect();
            BufferedInputStream bis = new BufferedInputStream(urlconnection.getInputStream());
            if (bis == null) {
                return "image/jpeg";
            } else {
                return HttpURLConnection.guessContentTypeFromStream(bis);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "image/jpeg";
        }
    }

    private String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 转换成bety[]
     */
    private byte[] readStream(InputStream inStream) throws Exception {
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            outStream.close();
            inStream.close();
            return outStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}
