package com.rv.component.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ShareUtils {


    /*******
     * 复制地址
     * @param url
     */
    public static void copy(Context context, String url) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newRawUri("Label", Uri.parse(url));
        cm.setPrimaryClip(mClipData);
        Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * view转bitmap
     */
    public static Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        int startX = (int) v.getX();
        int startY = (int) v.getY();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        v.layout(startX, startY, w + startX, h + startY);
        v.draw(c);
        return bmp;
    }

    public static File saveBitmapFile(Context context, Bitmap bitmap) {
        File parent = new File(StorageUtils.getPhotoSavePath(context));
        if (!parent.exists()) {
            parent.mkdirs();
        }
        File file = new File(parent, System.currentTimeMillis() + ".jpg");//将要保存图片的路径
        if (file.exists()) {
            return file;
        }
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        StorageUtils.notifyImageChange(context, file.getPath());
        return file;
    }
}
