package com.aplusinformatique.aplusmanager.Activitys;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.aplusinformatique.aplusmanager.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.intentfilter.androidpermissions.PermissionManager;
import com.intentfilter.androidpermissions.models.DeniedPermissions;

import static java.util.Collections.singleton;

public class Activity_ActivationGps extends AppCompatActivity {

    protected static final int REQUEST_CHECK_SETTINGS = 0x1;

    private boolean isSend = false;

    // ------- Success possibles -------
    // 0 : Tout est ok
    // 1 : Permission refusée
    // 2 : Permission ok, gps refusé
    // 3 : application tuée
    // 4 : Google Play pas à jour

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                checkGpsEnabled();
            } else {
                PermissionManager permissionManager = PermissionManager.getInstance(getApplicationContext());
                permissionManager.checkPermissions(singleton(Manifest.permission.ACCESS_FINE_LOCATION), new PermissionManager.PermissionRequestListener() {
                    @Override
                    public void onPermissionGranted() {
                        checkGpsEnabled();
                    }

                    @Override
                    public void onPermissionDenied(DeniedPermissions deniedPermissions) {
                        sendResponse(1);
                    }
                });
            }
        } else {
            checkGpsEnabled();
        }
    }

    private void checkGpsEnabled() {

        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            sendResponse(0);
        } else {
            Integer resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(Activity_ActivationGps.this);

            if (resultCode == ConnectionResult.SUCCESS) {
                displayLocationSettingsRequest(getApplicationContext());
            } else {
                Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, Activity_ActivationGps.this, 0);
                if (dialog != null) {
                    dialog.show();

                    dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            sendResponse(4);
                        }
                    });
                }
            }
        }
    }

    private void displayLocationSettingsRequest(Context context) {
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
                .addApi(LocationServices.API).build();
        googleApiClient.connect();

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(10000 / 2);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        sendResponse(2);

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            status.startResolutionForResult(Activity_ActivationGps.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            sendResponse(2);
                        }

                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        sendResponse(2);

                        break;
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        sendResponse(0);
                        break;
                    case Activity.RESULT_CANCELED:
                        sendResponse(2);
                        break;
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (!isSend) sendResponse(3);
    }

    private void sendResponse(int success) {
        isSend = true;

        Log.d("Manager", "code retour : " + success);

        Intent replyIntent = new Intent();
        replyIntent.setAction("com.aplusinformatique.aplusmanager.verificationreponse");
        replyIntent.putExtra("success", success);
        sendBroadcast(replyIntent);

        finish();
        overridePendingTransition(0, 0);
    }
}
