package jp.agentec.abook.abv.ui.home.helper;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;

import jp.agentec.abook.abv.bl.common.Callback;
import jp.agentec.abook.abv.bl.common.Constant;
import jp.agentec.abook.abv.cl.util.PreferenceUtil;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType;
import jp.agentec.abook.abv.ui.common.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.util.AlertDialogUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.util.PatternStringUtil;
import jp.agentec.abook.abv.ui.home.activity.OperationListActivity;
import jp.agentec.abook.abv.ui.viewer.activity.HTMLWebViewActivity;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static jp.agentec.abook.abv.cl.util.PreferenceUtil.getUserPref;

/**
 * 権限チェック及び設定画面遷移
 * Created by kim jinsung on 2018/09/21.
 */
public class ABookPermissionHelper {
    private Context mContext;
    private int mPermitionType;
    private AlertDialog mAlertDialog;
    private Callback mCallback;

    public ABookPermissionHelper(Context context, int permissionType, Callback callback) {
        mContext = context;
        mPermitionType = permissionType;
        mCallback = callback;
    }

    public ABookPermissionHelper(Context context) {
        mContext = context;
    }
    /**
     * AndroidOSバージョンアップ時の追加権限チェック
     * @return 権限文字列の配列
     */
    public ArrayList<String> checkAndroidVersionUpPermissions() {
        ArrayList<String> reqPermissions = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { //Android13以上
            boolean checkPermissionFlg = PreferenceUtil.getUserPref(mContext, AppDefType.UserPrefKey.ANDROID_13_PERMISSION_CHECK, true);
            if (checkPermissionFlg) {
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) {
                    reqPermissions.add(android.Manifest.permission.READ_MEDIA_VIDEO);
                }
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                    reqPermissions.add(android.Manifest.permission.READ_MEDIA_IMAGES);
                }
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                    reqPermissions.add(android.Manifest.permission.POST_NOTIFICATIONS);
                }
                PreferenceUtil.putUserPref(mContext, AppDefType.UserPrefKey.ANDROID_13_PERMISSION_CHECK, false);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { //Android14以上
                boolean android14PermissionCheckFlg = PreferenceUtil.getUserPref(mContext, AppDefType.UserPrefKey.ANDROID_14_PERMISSION_CHECK, true);
                if (android14PermissionCheckFlg) {
                    if (ContextCompat.checkSelfPermission(mContext,
                            android.Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) != PackageManager.PERMISSION_GRANTED) {
                        if (!checkPermissionFlg) {
                            reqPermissions.add(android.Manifest.permission.READ_MEDIA_VIDEO);
                            reqPermissions.add(android.Manifest.permission.READ_MEDIA_IMAGES);
                        }
                        reqPermissions.add(android.Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED);
                    }
                    PreferenceUtil.putUserPref(mContext, AppDefType.UserPrefKey.ANDROID_14_PERMISSION_CHECK, false);
                }
            }
        }
        return reqPermissions;
    }

    public ArrayList<String> checkMultiPermissions() {

        ArrayList<String> reqPermissions = new ArrayList<>();
        //Android6.0未満の場合はチェックしない
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return reqPermissions;
        }
        // 位置情報
        if (ContextCompat.checkSelfPermission(mContext,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            reqPermissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(mContext,
                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            reqPermissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        // ストレージ
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { //Android13以上
            if (ContextCompat.checkSelfPermission(mContext,
                    android.Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.READ_MEDIA_VIDEO);
            }
            if (ContextCompat.checkSelfPermission(mContext,
                    android.Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.READ_MEDIA_IMAGES);
            }
            if (ContextCompat.checkSelfPermission(mContext,
                    android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.POST_NOTIFICATIONS);
            }
            PreferenceUtil.putUserPref(mContext, AppDefType.UserPrefKey.ANDROID_13_PERMISSION_CHECK, false);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { //Android14以上
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) != PackageManager.PERMISSION_GRANTED) {
                    reqPermissions.add(android.Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED);
                    PreferenceUtil.putUserPref(mContext, AppDefType.UserPrefKey.ANDROID_14_PERMISSION_CHECK, false);
                }
            }

        } else {
            if (ContextCompat.checkSelfPermission(mContext,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(mContext,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        }

        // カメラ
        if (ContextCompat.checkSelfPermission(mContext,
                android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            reqPermissions.add(android.Manifest.permission.CAMERA);
        }
        // マイク（オーディオ）
        if (ContextCompat.checkSelfPermission(mContext,
                android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            reqPermissions.add(android.Manifest.permission.RECORD_AUDIO);
        }
        // Bluetooth
        if (Build.VERSION.SDK_INT > 30) {
            // Android12以上の場合
            if (ContextCompat.checkSelfPermission(mContext,
                    android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.BLUETOOTH_CONNECT);
            }
            if (ContextCompat.checkSelfPermission(mContext ,
                    android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.BLUETOOTH_SCAN);
            }
        } else {
            // Android12未満の場合
            if (ContextCompat.checkSelfPermission(mContext,
                    android.Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                reqPermissions.add(android.Manifest.permission.BLUETOOTH);
            }
        }
        return reqPermissions;
    }

    public boolean checkMultiPermissions(boolean showDialogFlg) {
        //Android6.0未満の場合はチェックしない
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }

        int permitionTextResourceId = -1;
        switch (mPermitionType) {
            case Constant.ABookPermissionType.ReadExternalStorage:
                // ストレージ
                boolean permissionGranted = true;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { //Android14以上
                    if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) != PERMISSION_GRANTED) {
                        permissionGranted = false;
                    }
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { //Android13以上
                    if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.READ_MEDIA_IMAGES) != PERMISSION_GRANTED) {
                        permissionGranted = false;
                    }
                } else {
                    // ストレージ
                    if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
                        permissionGranted = false;
                    }
                }
                if (!permissionGranted) {
                    if (mContext instanceof HTMLWebViewActivity ||
                            mContext instanceof OperationListActivity) {
                        // リソースパターンの適用
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { //Android13以上
                            permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                                    R.string.msg_permission_dialog_image_video,
                                    getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                        } else {
                            permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                                    R.string.msg_permission_dialog_storage_album,
                                    getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                        }
                    } else {
                        // リソースパターンの適用
                        permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                                R.string.msg_permission_dialog_storage_update,
                                getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                    }
                }
                break;
            case Constant.ABookPermissionType.AccessFineLocation:
                // 位置情報
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED) {
                    // リソースパターンの適用
                    permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                            R.string.msg_permission_dialog_location,
                            getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                }
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED) {
                    // リソースパターンの適用
                    permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                            R.string.msg_permission_dialog_location,
                            getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                }
                break;

            case Constant.ABookPermissionType.Camera:
                // カメラ
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.CAMERA) != PERMISSION_GRANTED) {
                    // リソースパターンの適用
                    permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                            R.string.msg_permission_dialog_camera,
                            getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                }
                break;
            case Constant.ABookPermissionType.Audio:
                // マイク(オーディオ）
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.RECORD_AUDIO) != PERMISSION_GRANTED) {
                    // リソースパターンの適用
                    permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                            R.string.msg_permission_dialog_mic,
                            getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                }
                break;
            case Constant.ABookPermissionType.Bluetooth:
                // Android12未満では実施しない
                if (Build.VERSION.SDK_INT < 31) {
                    break;
                }
                // Bluetooth
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.BLUETOOTH_CONNECT) != PERMISSION_GRANTED) {
                    // リソースパターンの適用
                    permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                            R.string.msg_permission_dialog_bluetooth,
                            getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                }
                if (ContextCompat.checkSelfPermission(mContext,
                        android.Manifest.permission.BLUETOOTH_SCAN) != PERMISSION_GRANTED) {
                    // リソースパターンの適用
                    permitionTextResourceId = PatternStringUtil.patternToInt(mContext,
                            R.string.msg_permission_dialog_bluetooth,
                            getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0));
                }
                break;
        }

        if (permitionTextResourceId > 0) {
            if (showDialogFlg) {
                ABookAlertDialog dialog = AlertDialogUtil.createABookAlertDialog(mContext);
                // リソースパターンの適用
                dialog.setTitle(PatternStringUtil.patternToString(mContext,
                                    R.string.title_permission_dialog,
                                    getUserPref(mContext, AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
                dialog.setMessage(permitionTextResourceId);
                dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", mContext.getPackageName(), null);
                        intent.setData(uri);
                        mContext.startActivity(intent);
                        if (mCallback != null) {
                            mCallback.callback(true);
                        }
                    }
                });
                dialog.setNegativeButton(R.string.cancel,  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mCallback != null) {
                            mCallback.callback(false);
                        }
                    }
                });
                if (mAlertDialog != null && this.mAlertDialog.isShowing()) {
                    mAlertDialog.dismiss();
                }
                this.mAlertDialog = dialog;
                mAlertDialog.show();
            }
            return false;
        }
        return true;
    }

}
