package com.ahau.againstpestinfo.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 注释:
 *
 * @author fanchunchun
 * @date 2018/5/6
 */

public class Utils {

    public static final String TAG = "Utils";
    public static final String THUMB_FOLDER = Settings.CACHE_DIR + "Thumb/";
    public final static int MINIMUM_SPACE = 200; // 50M

    public synchronized static Bitmap loadBitmap(String pathName, int outputW, int outputH, int rotate) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inDither = false;
        int width, height;
        Bitmap bmp = null;

        if (pathName == null || pathName.equals(""))
            return null;
        File file = new File(pathName);
        if (!file.exists())
            return null;

        options.inJustDecodeBounds = true;
        try {
            BitmapFactory.decodeFile(pathName, options);
        } catch (OutOfMemoryError e) {
            return null;

        }
        width = options.outWidth;
        height = options.outHeight;

        if (width == 0 || height == 0)
            return null;

        options.inDither = true;
        options.inJustDecodeBounds = false;

        if (outputW != 0 && outputH == 0) {
            outputH = height * outputW / width;
        } else if (outputW == 0 && outputH != 0) {
            outputW = width * outputH / height;
        }

        if (outputW != 0 && outputH != 0) {
            int ratio1 = 0;
            float ratioSrc = (float) width / (float) height;
            float ratioDes = (float) outputW / (float) outputH;
            if (ratioSrc < ratioDes && height > outputH) {
                outputW = outputH * width / height;
            }
            ratio1 = width / outputW;
            options.inSampleSize = ratio1;
        } else {
            options.inSampleSize = 1;
        }
        try {
            bmp = BitmapFactory.decodeFile(pathName, options);
        } catch (OutOfMemoryError e) {
            return null;
        }
        if (bmp == null) {
            return null;
        }

        // int orientation = utils.getPicOrientation(pathName);
        ExifInterface exif = null;
        int orientation = 0;
        try {
            exif = new ExifInterface(pathName);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (exif != null) {
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    orientation = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    orientation = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    orientation = 270;
                    break;
                default:
                    orientation = 0;
            }
        }
        // if(rotate != 0 && bmp.getWidth() > bmp.getHeight()) {
        // rotate = 90;
        // } else
        // rotate = 0;
        orientation += rotate;
        orientation %= 360;

        if (orientation != 0) {
            Matrix matrix = new Matrix();
            matrix.setRotate(orientation);

            Bitmap bmp2 = null;
            try {
                bmp2 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
            } catch (OutOfMemoryError e) {
                // Log.e("ZiiPhoto","can not create bitmap, out of memory!");
            }
            if (bmp2 != null) {
                bmp.recycle();
                bmp = bmp2;
            }
        }

        int bh = bmp.getHeight();
        if (outputH > 0 && bh > outputH) {
            outputW = outputH * bmp.getWidth() / bmp.getHeight();
            Bitmap sbmp = null;
            try {
                sbmp = Bitmap.createBitmap(outputW, outputH, Bitmap.Config.ARGB_8888);
            } catch (OutOfMemoryError e) {
                Utils.outLog("DecodeCache", "createStretchBitmap, OutOfMemoryError!");
            }
            if (sbmp != null) {
                Canvas canvas = new Canvas(sbmp);
                RectF dst = new RectF(0, 0, outputW, outputH);
                canvas.drawBitmap(bmp, null, dst, null);
                bmp.recycle();
                bmp = sbmp;
                canvas = null;
            }
        }

        return bmp;

    }

    public synchronized static Bitmap loadBitmap(String pathName, int largeSide, int shortSide) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inDither = false;
        float width, height;
        Bitmap bmp = null;

        if (pathName == null || pathName.equals(""))
            return null;

        File file = new File(pathName);
        if (!file.exists())
            return null;

        options.inJustDecodeBounds = true;
        try {
            BitmapFactory.decodeFile(pathName, options);
        } catch (OutOfMemoryError e) {
            return null;

        }
        width = options.outWidth;
        height = options.outHeight;

        if (width == 0 || height == 0)
            return null;

        options.inDither = true;
        options.inJustDecodeBounds = false;

        float outputW = width;
        float outputH = height;
        float zoomFit = 1.0f;
        double zoomGal = -1.0f;

        if (width > height) {
            outputW = largeSide;
            outputH = (int) (height * outputW / width);
        } else {
            outputW = shortSide;
            outputH = (int) (height * outputW / width);
        }
        zoomFit = (float) Math.min(outputH / height, outputW / width);
        if (zoomGal < 0) {
            zoomGal = zoomFit;
        }

        int ratio1 = 0;
        ratio1 = (int) (width / outputW);
        if (ratio1 < 1) {
            ratio1 = 1;
        }
        options.inSampleSize = ratio1;
        try {
            bmp = BitmapFactory.decodeFile(pathName, options);
        } catch (OutOfMemoryError e) {

            String memStr = "alloc memory: " + Runtime.getRuntime().totalMemory() + "; free memory:"
                    + Runtime.getRuntime().freeMemory() + "; max memory: " + Runtime.getRuntime().maxMemory();
            Utils.outLog("decodeBitmap OutOfMemoryError", memStr);
            Utils.outLog("decodeBitmap OutOfMemoryError", "options.inSampleSize=" + options.inSampleSize + " bw=" + width
                    + " bh=" + height + " ow=" + outputW + " oh=" + outputH);
            return null;
        }
        if (bmp == null) {
            return null;
        }

        ExifInterface exif = null;
        int orientation = 0;
        try {
            exif = new ExifInterface(pathName);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (exif != null) {
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    orientation = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    orientation = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    orientation = 270;
                    break;
                default:
                    orientation = 0;
            }
        }

        if (orientation != 0) {
            Matrix matrix = new Matrix();
            matrix.setRotate(orientation);

            Bitmap bmp2 = null;
            try {
                bmp2 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
            } catch (OutOfMemoryError e) {
                // Log.e("ZiiPhoto","can not create bitmap, out of memory!");
            }
            if (bmp2 != null) {
                bmp.recycle();
                bmp = bmp2;
            }
        }

        int bh = bmp.getHeight();
        if (outputH > 0 && bh > outputH) {
            outputW = outputH * bmp.getWidth() / bmp.getHeight();
            Bitmap sbmp = null;
            try {
                sbmp = Bitmap.createBitmap((int) outputW, (int) outputH, Bitmap.Config.ARGB_8888);
            } catch (OutOfMemoryError e) {
            }
            if (sbmp != null) {
                Canvas canvas = new Canvas(sbmp);
                RectF dst = new RectF(0, 0, outputW, outputH);
                canvas.drawBitmap(bmp, null, dst, null);
                bmp.recycle();
                bmp = sbmp;
                canvas = null;
            }
        }

        return bmp;
    }

    /**
     * create the folder with selected path.
     *
     * @param path
     */
    public static void createLocalDiskPath(String path) {
        File folder = new File(path);
        try {
            if (!folder.exists()) {

                boolean rtn = folder.mkdirs();
                outLog("createLocalDiskPath", "rtn=" + rtn);
            }
        } catch (Exception e) {
            outLog("createLocalDiskPath", "Exception");
        }
    }

    public static int getCurrentDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());
        String date = formatter.format(curDate);
        return Integer.valueOf(date);
    }

    public static int haveSpace() {
        long ret = readSDCard();
        int value = 0;
        long temp = ret / 1024 / 1024;
        if (temp > MINIMUM_SPACE)
            value = 0;
        else if (ret == -1)
            value = -1;
        else
            value = 1;
        return value;
    }

    static public long readSDCard() {
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            long blockSize = sf.getBlockSize();
            long blockCount = sf.getBlockCount();
            long availCount = sf.getAvailableBlocks();
            long freespace = availCount * blockSize;// / 1024 / 1024;
            Utils.outLog("", "block size:" + blockSize + ",blockcount:" + blockCount + ",size:" + blockSize * blockCount / 1024
                    + "KB");
            Utils.outLog("", "avail count:" + availCount + ",free space:" + availCount * blockSize / 1024 / 1024 + "MB");
            return freespace;
        } else {
            return -1;
        }

    }

    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
                int count=is.read(bytes, 0, buffer_size);
                if(count==-1)
                    break;
                os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }

    public static boolean deleteDirectory(String dir) {
        if (!dir.endsWith(File.separator)) {
            dir = dir + File.separator;
        }
        File dirFile = new File(dir);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            } else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            System.out.println("delete dir fail");
            return false;
        }

        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean deleteFile(String filePath) {
        if (filePath == null) {
            return false;
        }
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            file.delete();
            return true;
        } else {
            return false;
        }
    }



    public static void outLog(String tag, String msg) {
        Log.d(TAG, tag + " >>>>>>>>>>>>>>>>>> " + msg);
    }
}