package com.sheep.gamegroup.util;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.sheep.gamegroup.util.glide.BlurTransformation;
import com.sheep.gamegroup.util.glide.GlideCircleTransformWithBorder;
import com.sheep.gamegroup.util.glide.RoundedCornersTransformation;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.FileUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.Locale;

import okhttp3.Call;
import rx.functions.Action1;

/**
 * Created by realicing on 2018/3/26.
 * realicing@sina.com
 */

public class GlideImageLoader {

    public static void setBlur(ImageView imageView, String url) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().transform(new BlurTransformation()))
                .into(imageView);
    }
    public static void setImage(ImageView imageView, String url) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .into(imageView);
    }
    public static void setImage(ImageView imageView, String url, int id) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().placeholder(id))
                .into(imageView);
    }
    public static void setImageDisHardConfig(ImageView imageView, String url) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().disallowHardwareConfig())
                .into(imageView);
    }

    public static void centerImage(ImageView imageView, String url, int id) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().centerCrop().placeholder(id))
                .into(imageView);
    }

    public static void centerImage(ImageView imageView, String path) {
        Glide.with(SheepApp.getInstance())
                .load(path)
                .apply(new RequestOptions().centerCrop().placeholder(R.drawable.loading_01))
                .into(imageView);
    }

    public static void circleImage(ImageView imageView, String url, int id) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().circleCrop().placeholder(id))
                .into(imageView);
    }

    public static void circleImage(ImageView imageView, String url) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().circleCrop().placeholder(R.drawable.loading_01))
                .into(imageView);
    }

    public static void roundedCornersImage(ImageView imageView, String url, int radius, int id) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().transform(new RoundedCornersTransformation(radius, 0)).placeholder(id))
                .into(imageView);
    }

    public static void roundedCornersImage(ImageView imageView, String url, int radius) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().transform(new RoundedCornersTransformation(radius, 0)).placeholder(R.drawable.loading_01))
                .into(imageView);
    }
    public static void roundedCornersImage1(ImageView imageView, String url, int radius) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().centerCrop().transform(new RoundedCorners(radius)))
                .into(imageView);
    }
    public static void setGameImage(ImageView imageView, String url) {
        if(url.endsWith(".gif")){//gif图片不做任务处理
            Glide.with(SheepApp.getInstance())
                    .load(url)
                    .apply(new RequestOptions().placeholder(R.drawable.loading_01))
                    .into(imageView);
        } else {
            Glide.with(SheepApp.getInstance())
                    .load(url)
                    .apply(new RequestOptions().centerCrop().transform(new RoundedCorners(imageView.getResources().getDimensionPixelSize(R.dimen.content_padding_10))).placeholder(R.drawable.loading_01))
                    .into(imageView);
        }
    }
    public static void setGameImage(ImageView imageView, String url, int radius) {
        Glide.with(SheepApp.getInstance())
                .load(url)
                .apply(new RequestOptions().centerCrop().transform(new RoundedCorners(radius)).placeholder(R.drawable.loading_01))
                .into(imageView);
    }

    /**
     * 设置二维码图片
     * @param imageView
     * @param link
     * @param w
     */
    public static void saveAndSetRqImage(final ImageView imageView, String link, int w) {
        String fileName = String.format(Locale.CHINA, "%d.png", link.hashCode());
        File file = new File(ClassFileHelper.DIR, fileName);
        if(!file.exists()){
            Bitmap mBitmap = CodeUtils.createImage(link, w, w, null);
            if(mBitmap != null) {
                ViewUtil.saveImage(mBitmap, ClassFileHelper.DIR, fileName);
                if(imageView != null)
                    Glide.with(SheepApp.getInstance())
                            .load(file)
                            .apply(new RequestOptions().override(w, w))
                            .into(imageView);
            }
        }
        if(file.exists()){
            if(imageView != null)
                Glide.with(SheepApp.getInstance())
                        .load(file)
                        .apply(new RequestOptions().override(w, w))
                        .into(imageView);
        }
    }
    /**
     * 设置二维码图片
     * @param imageView
     * @param link
     * @param w
     */
    public static void saveAndSetRqImageDisHardConfig(final ImageView imageView, String link, int w) {
        String fileName = String.format(Locale.CHINA, "%d.png", link.hashCode());
        File file = new File(ClassFileHelper.DIR, fileName);
        if(!file.exists()){
            Bitmap mBitmap = CodeUtils.createImage(link, w, w, null);
            if(mBitmap != null) {
                ViewUtil.saveImage(mBitmap, ClassFileHelper.DIR, fileName);
                if(imageView != null)
                    Glide.with(SheepApp.getInstance())
                            .load(file)
                            .apply(new RequestOptions().disallowHardwareConfig().override(w, w))
                            .into(imageView);
            }
        }
        if(file.exists()){
            if(imageView != null)
                Glide.with(SheepApp.getInstance())
                        .load(file)
                        .apply(new RequestOptions().disallowHardwareConfig().override(w, w))
                        .into(imageView);
        }
    }


    public static void downloadAndSetImage(final ImageView imageView, final String link, final int w) {
        downLoadImage(String.format(Locale.CHINA, "%d", link.hashCode()), link, new Action1<File>() {
            @Override
            public void call(File file) {
                if(imageView != null) {
                    if (file == null)
                        Glide.with(SheepApp.getInstance())
                                .load(link)
                                .apply(new RequestOptions().override(w, w))
                                .into(imageView);
                    else
                        Glide.with(SheepApp.getInstance())
                                .load(file)
                                .apply(new RequestOptions().override(w, w))
                                .into(imageView);
                }

            }
        });

    }
    public static void downLoadImage(String name, String link, final Action1<File> action1) {
        String fileName = name + ".png";
        File file = new File(ClassFileHelper.DIR, fileName);
        if(file.exists()){
            if(action1 != null){
                action1.call(file);
            }
            return;
        }
        OkHttpUtils.get().url(link).build().execute(new FileCallBack(ClassFileHelper.DIR, fileName) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if(action1 != null){
                    action1.call(null);
                }
            }

            @Override
            public void onResponse(File response, int id) {
                if(response.exists()) {
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(response);
                    intent.setData(uri);
                    SheepApp.getInstance().sendBroadcast(intent); // 发送广播通知相册
                    if (action1 != null) {
                        action1.call(response);
                    }
                }
            }
        });
    }

    /**
     * 设置头像
     * @param iconImgIv
     * @param avatar
     */
    public static void setAvatar(ImageView iconImgIv, String avatar) {
        if(TextUtils.isEmpty(avatar)){
            Glide.with(SheepApp.getInstance())
                    .load(R.drawable.avatar)
                    .into(iconImgIv);
        } else {
            Glide.with(SheepApp.getInstance())
                    .load(avatar)
                    .apply(new RequestOptions().circleCrop().placeholder(R.drawable.avatar))
                    .into(iconImgIv);
        }
    }
    /**
     * 设置头像有外面的圆环
     * @param iconImgIv
     * @param avatar
     */
    public static void setAvatar(ImageView iconImgIv, String avatar, int color) {
        Object tag = iconImgIv.getTag(R.drawable.avatar);
        if(TextUtils.isEmpty(avatar)){
            if(tag instanceof String && tag.toString().isEmpty()){//防止重复加载
                return;
            }
            iconImgIv.setTag(R.drawable.avatar, "");
            Glide.with(SheepApp.getInstance())
                    .load(R.drawable.avatar)
                    .apply(new RequestOptions().override(iconImgIv.getMeasuredWidth()).transform(new GlideCircleTransformWithBorder(color)))
                    .into(iconImgIv);
        } else {
            if(tag instanceof String && tag.toString().equals(avatar)){//防止重复加载
                return;
            }
            iconImgIv.setTag(R.drawable.avatar, avatar);
            Glide.with(SheepApp.getInstance())
                    .load(avatar)
                    .apply(new RequestOptions().transform(new GlideCircleTransformWithBorder(color)).placeholder(R.drawable.avatar))
                    .into(iconImgIv);
        }
    }

    /**
     * 通过下载到本地的方式来加载图片并设置圆角与宽高，需要传入显示的宽度
     * @param name
     * @param link
     * @param imageView
     * @param width
     * @param radius
     */
    public static void downloadAndRoundedImage(String name, final String link, final ImageView imageView, final int width, final int radius) {
        GlideImageLoader.downLoadImage(name, link, new Action1<File>() {
            @Override
            public void call(File file) {
                if(file == null){
                    return;
                }
                BitmapFactory.Options options = FileUtil.getImageOptions(file);
                int w = options.outWidth;
                int h = options.outHeight;
//                int w = width;
//                int h = width * options.outHeight / options.outWidth;
                if(Math.abs(w-h) < Math.min(w, h)){
                    setImage(imageView, link);
                    return;
                }
                Glide.with(SheepApp.getInstance())
                        .load(file)
                        .apply(new RequestOptions().override(w, h).fitCenter().transform(new RoundedCorners(radius)))
                        .into(imageView);
            }
        });
    }
    /**
     * 通过下载到本地的方式来加载图片并设置圆角与宽高
     * @param name
     * @param link
     * @param imageView
     * @param radius
     */
    public static void downloadAndRoundedImage(String name, String link, final ImageView imageView, final int radius, final RequestListener<Drawable> listener) {
        GlideImageLoader.downLoadImage(name, link, new Action1<File>() {
            @Override
            public void call(File file) {
                if(file == null){
                    return;
                }
                BitmapFactory.Options options = FileUtil.getImageOptions(file);
                int w = options.outWidth;
                int h = options.outHeight;
//                int w = width;
//                int h = width * options.outHeight / options.outWidth;
                Glide.with(SheepApp.getInstance())
                        .load(file)
                        .listener(listener)
                        .apply(new RequestOptions().override(w, h).transform(new RoundedCorners(radius)))
                        .into(imageView);
            }
        });
    }
}
