package com.tsi.navi.helper;

import android.Manifest;
import android.app.Activity;
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.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class PermissionHelper {

    private static final int PERMISSION_REQUEST_CODE = 100;
    private Activity activity;
    private Context context;

    // 요청할 권한을 배열로 관리
    private String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };
    private int requestCount = 0;
    private int rejectCount = 0;

    public PermissionHelper(Activity activity, Context context) {
        this.activity = activity;
        this.context = context;
    }

    public boolean checkPermissions() {
        int result;
        List<String> permissionList = new ArrayList<>();
        rejectCount = 0;
        for (String permission : this.permissions) {
            result = ContextCompat.checkSelfPermission(this.context, permission);
            if (result != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
                requestCount++;
            }
        }
        return permissionList.isEmpty();
    }

    public void requestPermissions() {
        ActivityCompat.requestPermissions(this.activity, this.permissions, PERMISSION_REQUEST_CODE);
    }

    public boolean isRequestPermissionAll() {
        if (requestCount >= requestCount) {
            return true;
        }
        rejectCount++;
        return false;
    }

    public boolean permissionResult(int requestCode, @NotNull String[] permissions, @NotNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE && (grantResults.length > 0)) {
            for (int ii = 0; ii < grantResults.length; ii++) {
                if (grantResults[ii] == -1) {
                    // 결과가 0 이면 사용자가 허용한 것이고, -1 이면 거부한 것임
                    return false;
                }
            }
        }
        return true;
    }

    // 앱 설치 허용 확인
    public static void checkAppInstallation(Context context) {
        if (Build.VERSION.SDK_INT >= 26)
        {
            final Handler handler = new Handler(Looper.getMainLooper()){
                @Override
                public void handleMessage(Message msg)
                {
                    throw new RuntimeException();
                }
            };

            PackageManager packageManager = context.getPackageManager();
            if (!packageManager.canRequestPackageInstalls())
            {
                Toast toast = Toast.makeText(context, "APP Install permission", Toast.LENGTH_SHORT);
                toast.show();

                AlertDialog.Builder b = new AlertDialog.Builder(context);//, android.R.style.Theme_DeviceDefault_Light_Dialog);
                b.setCancelable(false); // 백버튼 불가, 바탕화면 클릭 불가
                b.setTitle("알림");
                b.setMessage("보안을 위해 스마트폰 환경설정의 '앱 설치 허용' 을 설정해 주시기 바랍니다. 설정화면으로 이동하시겠습니까?");
                b.setCancelable(false);
                b.setPositiveButton("설정하기", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                        intent.setData(Uri.parse("package:" + context.getPackageName()));
                        context.startActivity(intent);

                        handler.sendMessage(handler.obtainMessage());
                    }
                });

                b.setNegativeButton("건너띄기", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toast.cancel();
                        handler.sendMessage(handler.obtainMessage());
                    }
                });
                b.show();

                try {
                    Looper.loop();
                }
                catch(RuntimeException e) {
                    Toast.makeText(context, "uuuuuuuuuuuuuuuuuuuuuuuuu", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

}
