package kr.co.icontrols.iotplatform;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.PERMISSIONS;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.PERMISSION_ALL;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_PERMISSION_AGREE;

public class PermissionActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(hasPermissions(this, PERMISSIONS)){
            goToLoginActivity();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_PERMISSION_AGREE:
                if(resultCode == RESULT_OK) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == PERMISSION_ALL){
            boolean isGoToLoginActivity = true;
            for(int i = 0;i<permissions.length;i++){
                if(permissions[i].equals(android.Manifest.permission.CALL_PHONE) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(Manifest.permission.READ_EXTERNAL_STORAGE) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(android.Manifest.permission.CAMERA) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                } else if(permissions[i].equals(android.Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[i] != PERMISSION_GRANTED){
                    isGoToLoginActivity = false;
                }
            }

            if(isGoToLoginActivity){
                goToLoginActivity();
            } else {
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE,PopupActivity.MODE_YESNO);
                intent.putExtra(PopupActivity.POPUP_BODY_TEXT,getString(R.string.popup_set_permission));
                intent.putExtra(PopupActivity.POPUP_OK_BUTTON_TEXT,getString(R.string.setting));
                startActivityForResult(intent,RESULT_PERMISSION_AGREE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        final View fv = v;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e){
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);


        switch (v.getId()) {
            case R.id.btnPermission:
                if(needRequestRuntimePermissions()) {
                    if (!hasPermissions(this, PERMISSIONS)) {
                        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
                    } else {
                        goToLoginActivity();
                    }
                } else {
                    goToLoginActivity();
                }
                break;
        }
    }

    private boolean needRequestRuntimePermissions() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    private void goToLoginActivity(){
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
}
