package com.casic.dcms.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Environment;
import android.text.TextPaint;

import com.casic.dcms.base.BaseApplication;
import com.casic.dcms.utils.callback.IWaterMarkAddListener;
import com.pengxh.androidx.lite.hub.FloatHub;
import com.pengxh.androidx.lite.hub.LongHub;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import rx.Emitter;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ImageHelper {
    private static final String TAG = "ImageHelper";

    /**
     * 绘制文字到右下角并压缩图片
     */
    public static void drawTextToRightBottom(final Bitmap bitmap, IWaterMarkAddListener markAddListener) {
        Context context = BaseApplication.get();
        //初始化画笔
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTypeface(Typeface.DEFAULT);// 采用默认的宽度
        textPaint.setColor(Color.RED);
        textPaint.setDither(true); // 防抖动，获取更清晰的图像采样
        textPaint.setFilterBitmap(true);// 滤波

        String name = StringHelper.getUserBean().getAccount();
        String date = LongHub.timestampToDate(System.currentTimeMillis());
        String time = LongHub.timestampToTime(System.currentTimeMillis());

        Observable.<File>create(emitter -> {
            //图片像素不一样，字体也需要设置不一样,像素低的图片，文字要小
            textPaint.setTextSize(FloatHub.dp2px(context, 16));
            Rect nameBounds = new Rect();
            textPaint.getTextBounds(name, 0, name.length(), nameBounds);
            Rect dateBounds = new Rect();
            textPaint.getTextBounds(date, 0, date.length(), dateBounds);
            Rect timeBounds = new Rect();
            textPaint.getTextBounds(time, 0, time.length(), timeBounds);

            //添加水印
            Bitmap.Config bitmapConfig = bitmap.getConfig();
            if (bitmapConfig == null) {
                bitmapConfig = Bitmap.Config.RGB_565;
            }
            Bitmap copyBitmap = bitmap.copy(bitmapConfig, true);

            Canvas canvas = new Canvas(copyBitmap);
            final int bitmapWidth = copyBitmap.getWidth();
            final int bitmapHeight = copyBitmap.getHeight();

            //图片像素不一样，间距也需要设置不一样
            int padding, paddingRight, paddingBottom;
            padding = FloatHub.dp2px(context, 8);//两行水印间的间距
            paddingRight = FloatHub.dp2px(context, 12);
            paddingBottom = FloatHub.dp2px(context, 12);
            //有几行就写几行
            canvas.drawText(name, bitmapWidth - nameBounds.width() - paddingRight,
                    bitmapHeight - (dateBounds.height() + timeBounds.height() + 2 * padding + paddingBottom), textPaint);
            canvas.drawText(date, bitmapWidth - dateBounds.width() - paddingRight,
                    bitmapHeight - (timeBounds.height() + padding + paddingBottom), textPaint);
            canvas.drawText(time, bitmapWidth - timeBounds.width() - paddingRight,
                    bitmapHeight - paddingBottom, textPaint);

            //将带有水印的图片保存
            File waterImageDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "WaterImage");
            if (!waterImageDir.exists()) {
                waterImageDir.mkdir();
            }
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
            //index用来区分for循环太快会导致多想图片覆盖压缩问题
            File imageFile = new File(waterImageDir + File.separator + "IMG_" + timeStamp + ".png");
            if (!imageFile.exists()) {
                try {
                    imageFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                FileOutputStream fos = new FileOutputStream(imageFile);
                //以jpeg的编码方式，75%的像素质量保存为png图片
                copyBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
                fos.flush();
                fos.close();
                if (!copyBitmap.isRecycled()) {
                    copyBitmap.recycle();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            emitter.onNext(imageFile);
        }, Emitter.BackpressureMode.BUFFER).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<File>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(File file) {
                if (file != null) {
                    markAddListener.onSuccess(file);
                } else {
                    markAddListener.onError(new NullPointerException());
                }
            }
        });
    }
}
