package com.b2lmobitech.spottest;

import android.Manifest;
import android.app.AppOpsManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.b2lmobitech.spottest.frags.AccessAlerFragment;
import com.b2lmobitech.spottest.service.MoniterService;
import com.b2lmobitech.spottest.utils.PermissionSingleton;
import com.b2lmobitech.spottest.utils.Preference;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CALL_PHONE;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class SplashActivity extends AppCompatActivity {

    public static final int RequestPermissionCode = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Preference.getInstance(this).setExamStatus(false);
        //--swathi--//In sectionsactivity,Result activity i placed the lastActivity value
        Class<?> activityClass;

        try {
            SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
//            Toast.makeText(getApplicationContext(), "1="+prefs.getString("lastActivity", SplashActivity.class.getName()),Toast.LENGTH_SHORT).show();
            activityClass = Class.forName(
                    prefs.getString("lastActivity", SplashActivity.class.getName()));
        } catch(ClassNotFoundException ex) {
            activityClass = SplashActivity.class;
        }
//        Toast.makeText(this,"1="+activityClass.getName(),Toast.LENGTH_SHORT).show();
if(activityClass.getName().equalsIgnoreCase( SectionsActivity.class.getName()))
{
    startActivity(new Intent(this, activityClass));
}
else
{
    nextActivity();
}
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (nm != null) {
            nm.cancel(0);
        }
        //--swathi--//
        //nextActivity(); //--swathi commented--//
    }

    private void nextActivity(){
        if(checkPermission()) {
            requestPermission();
        }else if(!PermissionSingleton.getInstance(this).isUsageAccessAccessGranted()) {
            new AccessAlerFragment().showNow(getSupportFragmentManager(),"");
        }else if(Preference.getInstance(this).getStudentId().isEmpty()) {
            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
            finish();
        }else{
            startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
            finish();
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        nextActivity();
    }

    private void requestPermission() {

        ActivityCompat.requestPermissions(this, new String[]
                {
                        //CAMERA,
                        ACCESS_FINE_LOCATION,
                        WRITE_EXTERNAL_STORAGE,
                        READ_PHONE_STATE,
                        CALL_PHONE
                }, RequestPermissionCode);
    }

    public boolean checkPermission() {
       // int firstPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
        int ThirdPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
        int FourthPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), READ_PHONE_STATE);

        return  ThirdPermissionResult != PackageManager.PERMISSION_GRANTED ||
                FourthPermissionResult != PackageManager.PERMISSION_GRANTED;//firstPermissionResult != PackageManager.PERMISSION_GRANTED ||

    }

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

        switch (requestCode) {
            case RequestPermissionCode:

                if(checkPermission()){
                    askPermission();
                }else{
                    nextActivity();
                }
                break;
        }

    }

    private void askPermission(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

// Add the buttons
        builder.setPositiveButton("GO TO SETTING", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID)));
            }
        });

        builder.setNegativeButton("CLOSE APP" +
                "", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                finish();
            }
        });

        builder.setTitle("Permissions Required");
        builder.setMessage("Please enable all permissions");
        AlertDialog dialog = builder.create();
        dialog.show();
    }

}
