package com.usai.redant.CommonEditor;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;

import com.usai.redant.redantmobile.RedAntApplication;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Created by macmini1 on 2017/8/17.
 */

public class Utils {

    public static String getApplicationName(Context context) {

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

        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }

    public static Bitmap loadCacheImage(String path,Bitmap holder) {

//        System.gc();
//        try {
//            Context context = RedAntApplication.getInstance().getApplicationContext();
//            String file_path = Environment.getExternalStorageDirectory().getPath() + "/" + getApplicationName(context) + "/Cache/Image" + stringToMD5(path);
//            File file = new File(file_path);
//            if (!file.exists()) {
//                loadImage(path);
//                return holder;
//            }
//            Bitmap bitmap = BitmapFactory.decodeFile(file_path);
//            return bitmap;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return holder;

        return loadCacheImage(path,holder,false);
    }

    public static Bitmap loadCacheImage(String path,Bitmap holder, boolean remoteLoad) {
        System.gc();
        try {
            Context context = RedAntApplication.getInstance().getApplicationContext();
            String file_path = Environment.getExternalStorageDirectory().getPath() + "/" + getApplicationName(context) + "/Cache/Image" + stringToMD5(path);
            File file = new File(file_path);
            if (!file.exists()) {
                if (remoteLoad) {
                    loadImage(path);
                }
                return holder;
            }
            Bitmap bitmap = BitmapFactory.decodeFile(file_path);
            return bitmap;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return holder;
    }

    public static String cacheTmpImage(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }

        bitmap = compressBitmap(bitmap);

        Context context = RedAntApplication.getInstance().getApplicationContext();
        String file_path = Environment.getExternalStorageDirectory().getPath() + "/" + getApplicationName(context) + "/Cache/Tmp";
        File dir_file = new File(file_path);
        if (!dir_file.exists()) {
            dir_file.mkdirs();
        }
        file_path = file_path + UUID.randomUUID().toString();
        try {

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file_path));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();

            return file_path;
        } catch (IOException e) {
            e.printStackTrace();

        }

        return null;

    }

    public static void loadImage(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection cnn = null;
                Bitmap bitmap = null;
                try {
                    URL url = new URL(path);
                    cnn = (HttpURLConnection)url.openConnection();
                    cnn.setRequestMethod("GET");
                    cnn.setUseCaches(false);
                    cnn.setConnectTimeout(1500);
                    cnn.setReadTimeout(1500);
                    bitmap = BitmapFactory.decodeStream(cnn.getInputStream());

                    if (bitmap != null) {
                        cacheImage(path,bitmap);
                    }


                } catch (IOException e) {
                    e.printStackTrace();

                } finally {
                    if (cnn != null) {
                        cnn.disconnect();
                    }

                }
            }
        }).start();
    }

    public static void cacheLocalImageToURL(String path,String url) {


        String filename =stringToMD5(url);
        File file = new File(path);



        if (file.exists()) {

            Context context = RedAntApplication.getInstance().getApplicationContext();
            String file_path = Environment.getExternalStorageDirectory().getPath() + "/" + getApplicationName(context) + "/Cache/Image";
            File tmpF = new File(file_path);
            if (!tmpF.exists()) {
                tmpF.mkdirs();
            }
            file_path = file_path + "/" + filename;

            InputStream is = null;
            FileOutputStream os = null;
            try {
                is = new FileInputStream(file);
                os = new FileOutputStream(file_path);
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = is.read(buffer)) != -1) {
                    os.write(buffer,0,read);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {

                    os.flush();
                    os.close();
                    is.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    public static void cacheImage(String path,Bitmap bitmap) {


        bitmap = compressBitmap(bitmap);

        try {

            Context context = RedAntApplication.getInstance().getApplicationContext();
            String file_dir = Environment.getExternalStorageDirectory().getPath() + "/" + getApplicationName(context) + "/Cache/Image";
            File dir = new File(file_dir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String file_path = file_dir + "/" + stringToMD5(path);

            File file = new File(file_path);

            savePhotoToFile(bitmap,file);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private static Bitmap compressBitmap(Bitmap bitmap) {
        int width = 500;
        int height = 500;
        if (bitmap.getWidth() > width || bitmap.getHeight() > height) {
            bitmap = Bitmap.createScaledBitmap(bitmap,width,height,false);
        }
        return bitmap;
    }

    private static void savePhotoToFile(Bitmap bitmap, File photoFile) {
        if (photoFile == null || bitmap == null) {
            return;
        }
        try {

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(photoFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();

        } catch (IOException e) {
            e.printStackTrace();

        }
    }


    public static ProgressDialog waiting_alert(Context ctx,String title, String msg) {
        if (ctx == null) {
            return null;
        }
        ProgressDialog pd = new ProgressDialog(ctx);
        pd.setTitle(title);
        pd.setMessage(msg);

        pd.setCancelable(true);

        pd.show();

        return pd;
    }

    public static void message_alert(Context ctx,String title,String msg) {
        if (ctx == null) {
            return;
        }
        new AlertDialog.Builder(ctx)
                .setTitle(title)
                .setMessage(msg)
                .show();
    }




}
