package com.kfzs.cfyl.media.glide;

import android.graphics.Bitmap;
import android.support.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.kfzs.cfyl.media.bean.VideoFrame;
import com.kfzs.cfyl.media.util.VideoUtil;
import com.kfzs.cfyl.share_library.util.LogUtil;

import java.security.MessageDigest;
import java.util.Locale;

/**
 * Created by realicing on 2018/12/4.
 * realicing@sina.com
 */
public class VideoFrameTransform extends BitmapTransformation {

    private VideoFrame videoFrame;
    private boolean isTransform = true;

    public VideoFrameTransform(VideoFrame videoFrame) {
        super();
        this.videoFrame = videoFrame;
    }
    public VideoFrameTransform(VideoFrame videoFrame, boolean isTransform) {
        super();
        this.videoFrame = videoFrame;
        this.isTransform = isTransform;
    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        if(isTransform) {
            if(videoFrame.getWidth() > 100 || videoFrame.getHeight() > 100){
                int width = 100;
                int height = 100;
                if(videoFrame.getWidth() > videoFrame.getHeight()){
                    width = videoFrame.getWidth() * 100 / videoFrame.getHeight();
                } else {
                    height = videoFrame.getHeight() * 100 / videoFrame.getWidth();
                }
                return VideoUtil.getScaledFrameAtTime(videoFrame.setWidth(width).setHeight(height));
            } else {
                return VideoUtil.getFrameAtTime(videoFrame);
            }
        }
        return toTransform;
    }

    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {
        messageDigest.update((String.format(Locale.CHINA, "%s?w=%d&h=%d&time=%d", videoFrame.getVideoPath(), videoFrame.getWidth(), videoFrame.getHeight(), videoFrame.getAtTime())).getBytes(CHARSET));
    }
}
