package ai.pai.client.utils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.provider.MediaStore;

import com.android.common.utils.DeviceUtils;
import com.android.common.utils.LogHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ai.pai.client.beans.Album;
import ai.pai.client.beans.PhotoItem;

public class ImageUtils {

    public static int getCameraAlbumWidth(Context context) {
        return (DeviceUtils.getScreenWidth(context) - DeviceUtils.dip2px(context,4)) / 3 - DeviceUtils.dip2px(context,2);
    }


    public static Bitmap decodeBitmapWithSize(String pathName, int width, int height) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inInputShareable = true;
        options.inPurgeable = true;
        BitmapFactory.decodeFile(pathName, options);
        Matrix matrix = new Matrix();
        int originWidth = options.outWidth;
        int originHeight = options.outHeight;
        LogHelper.dfile("czy","照片上传 原始宽度="+originWidth + "原始高度="+originHeight);
        float ratioW = ((float)originWidth)/width;
        float ratioH = ((float)originHeight)/height;
        float ratio = ratioW > ratioH ? ratioH :ratioW;
        matrix.postScale(1/ratio,1/ratio);
        options.inJustDecodeBounds = false;
        Bitmap sourceBm = BitmapFactory.decodeFile(pathName, options);
        return Bitmap.createBitmap(sourceBm,0,0,originWidth,originHeight,matrix,true);
    }

     public static Bitmap decodeBitmapWithSize(String pathName, int width, int height,
                                               boolean useBigger) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inInputShareable = true;
        options.inPurgeable = true;
        BitmapFactory.decodeFile(pathName, options);

        int decodeWidth = width, decodeHeight = height;
        final int degrees = getImageDegrees(pathName);
        if (degrees == 90 || degrees == 270) {
            decodeWidth = height;
            decodeHeight = width;
        }

        if (useBigger) {
            options.inSampleSize = (int) Math.min(((float) options.outWidth / decodeWidth),
                    ((float) options.outHeight / decodeHeight));
        } else {
            options.inSampleSize = (int) Math.max(((float) options.outWidth / decodeWidth),
                    ((float) options.outHeight / decodeHeight));
        }

        options.inJustDecodeBounds = false;
        Bitmap sourceBm = BitmapFactory.decodeFile(pathName, options);
        return imageWithFixedRotation(sourceBm, degrees);
    }

    public static int getImageDegrees(String pathName) {
        int degrees = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(pathName);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degrees = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degrees = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degrees = 270;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return degrees;
    }

    public static Bitmap imageWithFixedRotation(Bitmap bm, int degrees) {
        if (bm == null || bm.isRecycled())
            return null;

        if (degrees == 0)
            return bm;

        final Matrix matrix = new Matrix();
        matrix.postRotate(degrees);
        Bitmap result = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        if (result != bm)
            bm.recycle();
        return result;

    }

    public static Map<String, Album> findGalleries(Context mContext, List<String> paths) {
        paths.clear();
        paths.add(FileUtils.getInst().getSystemPhotoPath());
        String QQDir = "/mnt/sdcard/tencent/QQ_Images";
        String WXDir = "/mnt/sdcard/tencent/MicroMsg/WeiXin";
        paths.add(QQDir);
        paths.add(WXDir);
        String[] projection = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED };
        long startTime = System.currentTimeMillis()-1000*60*60*24*7L;
        startTime = startTime/1000;
        Cursor cursor = mContext.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,//指定所要查询的字段
                MediaStore.Images.Media.SIZE + ">? and "+ MediaStore.Images.Media.DATE_ADDED+" > ?" ,//查询条件
                new String[] { "10000",String.valueOf(startTime) }, //查询条件中问号对应的值
                MediaStore.Images.Media.DATE_ADDED + " desc");

        cursor.moveToFirst();
        //文件夹照片
        Map<String, Album> galleries = new HashMap<String, Album>();
        while (cursor.moveToNext()) {
            String data = cursor.getString(1);
            if (data.lastIndexOf("/") < 1) {
                continue;
            }
            if(data.contains("lensman")||data.contains("paiai")){
                continue;
            }
            String sub = data.substring(0, data.lastIndexOf("/"));
            if (!galleries.keySet().contains(sub)) {
                String name = sub.substring(sub.lastIndexOf("/") + 1, sub.length());
                if (!paths.contains(sub)) {
                    paths.add(sub);
                }
                galleries.put(sub, new Album(name, sub, new ArrayList<PhotoItem>()));
            }

            galleries.get(sub).getPhotos().add(new PhotoItem(data, (long) (cursor.getInt(2)) * 1000));
        }
        cursor.close();
        //系统相机照片
        ArrayList<PhotoItem> sysPhotos = FileUtils.getInst().findPicsInDir(
                FileUtils.getInst().getSystemPhotoPath());
        if (!sysPhotos.isEmpty()) {
            galleries.put(FileUtils.getInst().getSystemPhotoPath(), new Album("胶卷相册", FileUtils
                    .getInst().getSystemPhotoPath(), sysPhotos));
        } else {
            galleries.remove(FileUtils.getInst().getSystemPhotoPath());
            paths.remove(FileUtils.getInst().getSystemPhotoPath());
        }

        ArrayList<PhotoItem> tencentPhotos = FileUtils.getInst().findPicsInDir(
                QQDir);
        if (!tencentPhotos.isEmpty()) {
            galleries.put(QQDir, new Album("QQ", QQDir, tencentPhotos));
        } else {
            galleries.remove(QQDir);
            paths.remove(QQDir);
        }

        ArrayList<PhotoItem> wxPhotos = FileUtils.getInst().findPicsInDir(
                WXDir);
        if (!wxPhotos.isEmpty()) {
            galleries.put(WXDir, new Album("WeiXin", WXDir, wxPhotos));
        } else {
            galleries.remove(WXDir);
            paths.remove(WXDir);
        }
        return galleries;
    }
}
