package com.ama.core.architecture.util.permission;



import static com.ama.core.architecture.util.permission.PermissionUtil.PERMISSION_BROADCAST_ACTION;
import static com.ama.core.architecture.util.permission.PermissionUtil.PERMISSION_BROADCAST_ACTION_EXTRA_RESULT;
import static com.ama.core.architecture.util.permission.PermissionUtil.PERMISSION_BROADCAST_ACTION_EXTRA_UUID;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.ama.core.architecture.R;
import com.ama.core.architecture.util.ResUtil;
import java.util.ArrayList;


public class PermissionActivity extends AppCompatActivity {
    public static final int PERMISSION_REQUEST_CODE = 1000;
    private static final String PERMISSION_TOTAL_REJECTED_HINT = ResUtil.INSTANCE.getString(R.string.permission_hint);

    public static final String EXTRA_PERMISSION = "extra_permission";
    public static final String EXTRA_ACTION_UUID = "extra_callback";

    private String mActionUUID;
    private ArrayList<String> mPermissionList;













    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarColor(this, Color.TRANSPARENT);
        setNavigationBarColor(this, Color.TRANSPARENT);

        mActionUUID = getIntent().getStringExtra(EXTRA_ACTION_UUID);
        mPermissionList = getIntent().getStringArrayListExtra(EXTRA_PERMISSION);
        startRequest();
    }


    private void startRequest() {
        if (mActionUUID == null || mPermissionList == null && mPermissionList.size() <= 0) {
            finish();
        }


        ActivityCompat.requestPermissions(PermissionActivity.this,
                mPermissionList.toArray(new String[mPermissionList.size()]), PERMISSION_REQUEST_CODE);

    }





    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (PERMISSION_REQUEST_CODE == requestCode) {
            if (grantResults == null || grantResults.length <= 0) {
                sendResultBroadCast(PermissionUtil.PERMISSION_RESULT_ALL_REJECTED);
            } else {
                int grantedCount = 0;
                int unGrantedCount = 0;
                for (int result : grantResults) {
                    if (result == PackageManager.PERMISSION_GRANTED) {
                        grantedCount++;
                    } else {
                        unGrantedCount++;
                    }
                }

                if (unGrantedCount <= 0) {
                    sendResultBroadCast(PermissionUtil.PERMISSION_RESULT_ALL_GRANTED);
                } else {
                    int finalGrantedCount = grantedCount;
                    StringBuilder unGrantedPermissionsStr =  new StringBuilder();
                    for (int i=0; i<permissions.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED
                                && permissions[i].contains(".")
                                && !permissions[i].endsWith(".")) {

                            unGrantedPermissionsStr.append("[" + permissions[i].substring(permissions[i].lastIndexOf(".") + 1) + "] ");
                        }
                    }
                    new AlertDialog.Builder(this)
                            .setTitle("权限已被拒绝")
                            .setMessage(PERMISSION_TOTAL_REJECTED_HINT + unGrantedPermissionsStr)
                            .setPositiveButton("系统设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                    startActivity(intent);

                                    sendResultBroadCast(finalGrantedCount > 0 ? PermissionUtil.PERMISSION_RESULT_PARTIAL_GRANTED : PermissionUtil.PERMISSION_RESULT_ALL_REJECTED);
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    sendResultBroadCast(finalGrantedCount > 0 ? PermissionUtil.PERMISSION_RESULT_PARTIAL_GRANTED : PermissionUtil.PERMISSION_RESULT_ALL_REJECTED);
                                }
                            })
                            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    sendResultBroadCast(finalGrantedCount > 0 ? PermissionUtil.PERMISSION_RESULT_PARTIAL_GRANTED : PermissionUtil.PERMISSION_RESULT_ALL_REJECTED);
                                }
                            })
                            .create()
                            .show();
                }
            }
        }
    }


    /**
     * 用户选择了"不再询问", 引导用户跳转系统设置
     */
    private void showJump2SystemSettingDialog() {



        // new
        new AlertDialog.Builder(this)
                .setTitle("权限已被拒绝")
                .setMessage(mPermissionList + PERMISSION_TOTAL_REJECTED_HINT)
                .setPositiveButton("系统设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                    }
                })
                .create()
                .show();
    }


    private void sendResultBroadCast(int permissionResult) {
        Intent intent = new Intent(PERMISSION_BROADCAST_ACTION);
        intent.putExtra(PERMISSION_BROADCAST_ACTION_EXTRA_RESULT, permissionResult);
        intent.putExtra(PERMISSION_BROADCAST_ACTION_EXTRA_UUID, mActionUUID);
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
        finish();
    }




    //******************************** Static Methods *********************************//
    private static void setStatusBarColor(Activity activity, int colorId) {
        Window window = activity.getWindow();
        window.setStatusBarColor(colorId);
    }

    private static void setNavigationBarColor(Activity activity, int colorId) {
        Window window = activity.getWindow();
        window.setNavigationBarColor(colorId);
    }

    private static void setTranslucentStatus(Window window) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = window.getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams attributes = window.getAttributes();
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            attributes.flags |= flagTranslucentStatus;
            window.setAttributes(attributes);
        }
    }

}
