package com.yidianling.uikit.business.session.actions;

import android.Manifest;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.lzy.imagepicker.bean.ImageItem;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ydl.ydlcommon.actions.imagepicker.PickerCallback;
import com.ydl.ydlcommon.actions.imagepicker.YdlImagePicker;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.nimbase.business.session.actions.BaseAction;
import com.yidianling.nimbase.common.ToastHelper;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by zhoujianghua on 2015/7/31.
 */
public abstract class PickImageAction extends BaseAction {

    private static final int PICK_IMAGE_COUNT = 9;
    private static final int PORTRAIT_IMAGE_WIDTH = 720;

    public static final String MIME_JPEG = "image/jpeg";
    public static final String JPG = ".jpg";

    private boolean multiSelect;
    private boolean crop = false;

    protected abstract void onPicked(File file);

    protected PickImageAction(int iconResId, int titleId, boolean multiSelect) {
        super(iconResId, titleId);
        this.multiSelect = multiSelect;

    }

    @Override
    public void onClick() {
        new RxPermissions(getActivity()).requestEach(Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    if (permission.granted) {
                        selectImage();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        ToastUtil.toastShort("权限被拒绝，无法选择图片");
                    } else {
                        ToastUtil.toastShort("请到应用设置中开启相机权限");
                    }
                }, throwable -> {
                    Log.i("PickImageAction",throwable.getMessage());
                });
    }

    private void selectImage(){
        YdlImagePicker.INSTANCE.startPicker((AppCompatActivity) getActivity(), false, new PickerCallback() {
            @Override
            public void onSuccess(@NotNull ArrayList<ImageItem> images) {
                for (int i = 0; i < images.size(); i++) {
                    onPicked(new File(images.get(i).path));
                }
            }

            @Override
            public void onFail() {
                ToastHelper.showToast(getActivity(), R.string.im_picker_image_error);
            }
        });
    }

}
