package com.meeting.demo.dependency;

import android.app.Activity;
import android.content.Intent;
import android.provider.MediaStore;

import com.huawei.clpermission.CLPPermissionGrentListener;
import com.huawei.clpermission.CLPermissionHelper;
import com.huawei.hwmconf.presentation.constant.Constants;
import com.huawei.hwmconf.presentation.dependency.IVirtualBackgroundHandle;
import com.huawei.hwmconf.presentation.eventbus.ImagePickerState;
import com.huawei.hwmconf.presentation.util.PermissionUtil;
import com.meeting.demo.utils.DemoUtil;
import com.huawei.hwmfoundation.utils.SecurityUtils;

import org.greenrobot.eventbus.EventBus;

public class CustomVirtualBackgroundHandle implements IVirtualBackgroundHandle {
    @Override
    public void onClickAddVirtualBackgroundItem(Activity curActivity) {
        DemoUtil.showToast("跳转自定义界面设置虚拟背景");
        showPictureActivity(curActivity);
    }

    public void showPictureActivity(Activity curActivity) {
        if (permissionsGranted(curActivity)) {
            goSystemAlbum(curActivity);
        } else {
            requestPermission(curActivity);
        }
    }

    private boolean permissionsGranted(Activity curActivity) {
        return CLPermissionHelper.hasPermissionWithType(curActivity, PermissionUtil.getMediaImagesPermissionType());
    }

    public void goSystemAlbum(Activity curActivity) {
        EventBus.getDefault().post(new ImagePickerState(true));
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        try {
            SecurityUtils.safeStartActivityForResult(curActivity, intent, Constants.IMAGE_REQUEST_CODE);
        } catch (Exception e) {
            DemoUtil.showToast("请求打开系统图库失败！");
        }
    }

    private void requestPermission(Activity curActivity) {
        String type = PermissionUtil.getMediaImagesPermissionType();
        int requestCode = PermissionUtil.getMediaImagesPermissionRequestCode();
        PermissionUtil.requestPermission(curActivity, type, requestCode, new CLPPermissionGrentListener() {
            @Override
            public void onGrant() {
                goSystemAlbum(curActivity);
            }

            @Override
            public void onDeny() {
                DemoUtil.showToast("请求允许应用程序访问设备的存储空间失败！");
            }
        });
    }
}
