package com.renitha.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

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

import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

import com.google.gson.Gson;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.renitha.BuildConfig;
import com.renitha.Interface.APIService;
import com.renitha.Model.APIUrl;
import com.renitha.Model.SetterLogin;
import com.renitha.Model.SetterPMScalls;
import com.renitha.Pref.Pref;
import com.renitha.R;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserDoneComplaintActivity extends AppCompatActivity
{
    // location last updated time
    private String mLastUpdateTime;
    private Double lat=0.0;
    private Double longi=0.0;
    // location updates interval - 10sec
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
    // fastest updates interval - 5 sec
    // location updates will be received if another app is requesting the locations
    // than your app can handle
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
    private static final int REQUEST_CHECK_SETTINGS = 100;

    // bunch of location related apis
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationRequest mLocationRequest;
    private LocationSettingsRequest mLocationSettingsRequest;
    private LocationCallback mLocationCallback;
    private Location mCurrentLocation;
    private static final int REQUEST_CAMERA = 1;
    private static String[] PERMISSIONS_CAMERA = {
            Manifest.permission.CAMERA
    };
    // boolean flag to toggle the ui
    private Boolean mRequestingLocationUpdates=false;

    private static SimpleDateFormat dateFormat;
    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private TextView total_time;
    private EditText editTextCallNo,editTextFaultDetails,editTextServicePerformed,editTextPreventive,editTextBreakDown,editTextJobDate,editTextStartTime,editTextEndTime;
    private Button btnNext;
    String id,flag,ticket_no;
    String formattedDate;
    private String selectedStartTimingValue="";
    private String selectedEndTimingValue="",tot_time="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_completed_details);

        Bundle bundle           =       getIntent().getExtras();
        id                      =       bundle.getString("id");
        flag                    =       bundle.getString("flag");
        ticket_no               =       bundle.getString("ticket_no");

        editTextCallNo          =   (EditText)findViewById(R.id.editTextCallNo);
        editTextFaultDetails    =   (EditText)findViewById(R.id.editTextFaultDetails);
        editTextServicePerformed=   (EditText)findViewById(R.id.editTextServicePerformed);
        editTextPreventive      =   (EditText)findViewById(R.id.editTextPreventive);
        editTextBreakDown       =   (EditText)findViewById(R.id.editTextBreakDown);
        editTextJobDate         =   (EditText)findViewById(R.id.editTextJobDate);
        editTextStartTime       =   (EditText)findViewById(R.id.editTextStartTime);
        editTextEndTime         =   (EditText)findViewById(R.id.editTextEndTime);
        total_time              =   (TextView) findViewById(R.id.total_time);
        btnNext                 =   (Button)findViewById(R.id.btnNext);

        //dateFormat            =    new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.getDefault());
        dateFormat            =    new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
        final Calendar c      =    Calendar.getInstance();
        year                  =    c.get(Calendar.YEAR);
        month                 =    c.get(Calendar.MONTH);
        day                   =    c.get(Calendar.DAY_OF_MONTH);
        hour                  =    c.get(Calendar.HOUR);
        minute                =    c.get(Calendar.MINUTE);

        formattedDate = dateFormat.format(new Date()).toString();
        editTextJobDate.setText(formattedDate);
        editTextCallNo.setText(ticket_no);
        editTextJobDate.setEnabled(false);
        editTextCallNo.setEnabled(false);

        editTextStartTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP)
                {
                    // Get Current Time
                    // TODO Auto-generated method stub
                    final Calendar mcurrentTime = Calendar.getInstance();
                    int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                    int minute = mcurrentTime.get(Calendar.MINUTE);

                    TimePickerDialog mTimePicker;
                    mTimePicker = new TimePickerDialog(UserDoneComplaintActivity.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                            Calendar temp=Calendar.getInstance();
                            temp.set(Calendar.HOUR_OF_DAY,selectedHour);
                            temp.set(Calendar.MINUTE,selectedMinute);
                            String s = checkDigit(selectedHour) + ":" + selectedMinute;
                            DateFormat f1 = new SimpleDateFormat("HH:mm"); //HH for hour of the day (0 - 23)
                            Date d = null;
                            try
                            {
                                d = f1.parse(s);
                            } catch (ParseException e)
                            {
                                e.printStackTrace();
                            }
                            if(temp.after(GregorianCalendar.getInstance())){
                                selectedStartTimingValue= "";
                                editTextStartTime.setText("");
                                Toast.makeText(getApplicationContext(), "Cannot select a future time", Toast.LENGTH_SHORT).show();
                            }
                            else{
                                DateFormat f2 = new SimpleDateFormat("hh:mm a");
                                selectedStartTimingValue= f2.format(d).toUpperCase();
                                editTextStartTime.setText(f2.format(d).toUpperCase() );
                            }
                        }
                    }, hour, minute, false);//Yes 24 hour time
                    mTimePicker.setTitle("Select Time");
                    mTimePicker.show();
                }
                return false;
            }
        });

        editTextEndTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP) {

                    // Get Current Time
                    // TODO Auto-generated method stub
                    final Calendar mcurrentTime = Calendar.getInstance();
                    int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                    int minute = mcurrentTime.get(Calendar.MINUTE);

                    TimePickerDialog mTimePicker;

                    mTimePicker = new TimePickerDialog(UserDoneComplaintActivity.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {

                            Calendar temp=Calendar.getInstance();
                            temp.set(Calendar.HOUR_OF_DAY,selectedHour);
                            temp.set(Calendar.MINUTE,selectedMinute);
                            String s = checkDigit(selectedHour) + ":" + selectedMinute;
                            DateFormat f1 = new SimpleDateFormat("HH:mm"); //HH for hour of the day (0 - 23)


                            String start_time   =   editTextStartTime.getText().toString();
                             try {
                                 Date strt_date = f1.parse(start_time);
                                 Date end_date = f1.parse(s);


                                 if(temp.after(GregorianCalendar.getInstance())){
                                     selectedEndTimingValue= "";
                                     editTextEndTime.setText("");
                                     Toast.makeText(getApplicationContext(), "Cannot select a future time", Toast.LENGTH_SHORT).show();
                                 }
                                 else{
                                     DateFormat f2 = new SimpleDateFormat("hh:mm a");
                                     selectedEndTimingValue= f2.format(end_date).toUpperCase();
                                     editTextEndTime.setText(f2.format(end_date).toUpperCase());
                                 }
                                 /*Date strt_date1 = f1.parse(start_time);
                                 Date end_date1 = f1.parse(selectedEndTimingValue);
                                 if(strt_date1.after(end_date1)) {
                                     //Toast.makeText(getApplicationContext(), "Start time is greater than end time ", Toast.LENGTH_LONG).show();

                                 } else {

                                     selectedEndTimingValue= "";
                                     editTextEndTime.setText("");
                                     total_time.setText("Total Time : ");
                                     tot_time="";
                                     Toast.makeText(getApplicationContext(), "End time must be greater than start time", Toast.LENGTH_LONG).show();

                                 }*/

                             } catch (ParseException e)
                            {
                                e.printStackTrace();
                            }

                          /*  if (UserDoneComplaintActivity.isTimeAfter(strt_date, end_date)) {
                                //Toast.makeText(AddActivity.this, "Time validation success", Toast.LENGTH_LONG).show();
                                //DateFormat f2 = new SimpleDateFormat("h:mm a");
                                //selectedEndTimingValue= f2.format(end_date).toUpperCase();
                               // editTextEndTime.setText(f2.format(end_date).toUpperCase() );

                            }
                            else {
                                selectedEndTimingValue= "";
                                editTextEndTime.setText("");
                                Toast.makeText(getApplicationContext(), "Exit time must be greater then entry time", Toast.LENGTH_LONG).show();
                            }*/
                           /* SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                            Date startDate = simpleDateFormat.parse("22:00");
                            Date endDate = simpleDateFormat.parse("07:00");*/
                            try {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa");
                                Date date1 = simpleDateFormat.parse(start_time);
                                Date date2 = simpleDateFormat.parse(selectedEndTimingValue);
                                long difference = ( date2.getTime() - date1.getTime()) / 1000;
                                long min = 0;
                                long hours = difference % (24 * 3600) / 3600; // Calculating Hours
                                long minute = difference % 3600 / 60; // Calculating minutes if there is any minutes difference
                                // min = minute + (hours * 60);
                                if(hours<0 || minute<0)
                                {
                                    selectedEndTimingValue= "";
                                    editTextEndTime.setText("");
                                    total_time.setText("Total Time : ");
                                    tot_time="";
                                    Toast.makeText(getApplicationContext(), "End time must be greater than start time", Toast.LENGTH_LONG).show();

                                }
                                else if(hours==0 && minute==0)
                                {
                                    selectedEndTimingValue= "";
                                    editTextEndTime.setText("");
                                    total_time.setText("Total Time : ");
                                    tot_time="";
                                    Toast.makeText(getApplicationContext(), "End time and start time is not equals", Toast.LENGTH_LONG).show();

                                }
                                else {
                                    total_time.setText("Total Time : " + hours + " Hrs " + minute + " Mins");
                                    tot_time = hours + " Hrs " + minute + " Mins";
                                }
                            }
                            catch (ParseException e)
                            {
                                e.printStackTrace();
                            }

                            /*if(difference<0)
                            {
                                try {
                                    Date dateMax = f1.parse("24:00");
                                    Date dateMin = f1.parse("00:00");
                                    difference=(dateMax.getTime() -strt_date.getTime() )+(end_date.getTime()-dateMin.getTime());

                                }
                                catch (ParseException e)
                                {
                                    e.printStackTrace();
                                }
                            }*/
                            //int days = (int) (difference / (1000*60*60*24));
                            //int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
                            //int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
                            //Log.i("log_tag","Hours: "+hours+", Mins: "+min);
                           // Toast.makeText(getApplicationContext(), "Hours: "+hours+", Mins: "+min, Toast.LENGTH_SHORT).show();

                        }
                    }, hour, minute, false);//Yes 24 hour time
                    mTimePicker.setTitle("Select Time");
                    mTimePicker.show();
                }
                return false;
            }
        });
        init();
        get_pms();
        // restore the values from saved instance state
        restoreValuesFromBundle(savedInstanceState);
     //   dexter();
        startLocationUpdates();
        verifyStoragePermissions(this);

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editTextFaultDetails.getText().equals(""))
                {
                    showAlert("Please enter fault details");
                }
                else if(editTextServicePerformed.getText().equals(""))
                {
                    showAlert("Please enter service performed");
                }
                else if(editTextStartTime.getText().equals(""))
                {
                    showAlert("Please select start time");
                }
                else if(editTextEndTime.getText().equals(""))
                {
                    showAlert("Please select end time");
                }
                else {
                    save_info();
                }
            }
        });
    }
    public static boolean isTimeAfter(Date startTime, Date endTime) {
        return !endTime.before(startTime);
    }

    private void save_info()
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Saving...");
        progressDialog.show();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.MINUTES)
                .writeTimeout(20, TimeUnit.MINUTES)
                .readTimeout(20, TimeUnit.MINUTES).build();
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        // add your other interceptors …
        // add logging as last interceptor
        httpClient.addInterceptor(logging);  // <-- this is the important line
        //.client(httpClient.build())

        String CallNo           =   editTextCallNo.getText().toString().trim();
        String FaultDetails     =   editTextFaultDetails.getText().toString().trim();
        String ServicePerformed =   editTextServicePerformed.getText().toString().trim();
        String Preventive       =   editTextPreventive.getText().toString().trim();
        String BreakDown        =   editTextBreakDown.getText().toString().trim();
        String JobDate          =   editTextJobDate.getText().toString().trim();
        String StartTime        =   editTextStartTime.getText().toString().trim();
        String EndTime          =   editTextEndTime.getText().toString().trim();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .build();
        String login_id             =   Pref.getInstance(getApplicationContext()).getLoginId();
        // ticket_entry_id =   Pref.getInstance(getApplicationContext()).getTICKET_ID();
        APIService service = retrofit.create(APIService.class);
        Call<SetterLogin> call = service.setComplaintDone(id,flag,CallNo, FaultDetails, ServicePerformed,Preventive,BreakDown,JobDate,StartTime,EndTime,tot_time,lat,longi,login_id);

        call.enqueue(new Callback<SetterLogin>()
        {
            @Override
            public void onResponse(Call<SetterLogin> call, Response<SetterLogin> response)
            {
                progressDialog.dismiss();
                if (response.body().getError().equals(true))
                {
                    Pref.getInstance(getApplicationContext()).setTICKET_ID(response.body().getLogin_id());

                    startActivity(new Intent(UserDoneComplaintActivity.this, UploadPhotoActivity.class));
                    overridePendingTransition(R.anim.enter, R.anim.exit);
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Information saved Failed", Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onFailure(Call<SetterLogin> call, Throwable t)
            {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }


    private void get_pms()
    {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        // add your other interceptors …
        // add logging as last interceptor
        httpClient.addInterceptor(logging);  // <-- this is the important line
        //.client(httpClient.build())

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .client(httpClient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService service = retrofit.create(APIService.class);
        Call<SetterPMScalls> call = service.getPMSCallResult(id);

        call.enqueue(new Callback<SetterPMScalls>()
        {
            @Override
            public void onResponse(Call<SetterPMScalls> call, Response<SetterPMScalls> response)
            {
                if (response.body().getError().equals(true))
                {
                    editTextBreakDown.setEnabled(false);
                    editTextPreventive.setEnabled(false);
                    editTextPreventive.setText(response.body().getPms());
                    editTextBreakDown.setText(response.body().getBreak_down());
                }
            }
            @Override
            public void onFailure(Call<SetterPMScalls> call, Throwable t)
            {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
    public void showAlert(String message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(Html.fromHtml("<font color='#8472BB'>"+message+"!</font>")).setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        dialog.dismiss();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
        Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
        pbutton.setTextColor(Color.BLACK);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        // Resuming location updates depending on button state and
        // allowed permissions
        if (mRequestingLocationUpdates && checkPermissions())
        {
            startLocationUpdates();
        }
        updateLocationUI();
    }
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);

        if (permission != PackageManager.PERMISSION_GRANTED)
        {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_CAMERA,
                    REQUEST_CAMERA
            );
        }
    }
    private  void dexter()
    {
        // Requesting ACCESS_FINE_LOCATION using Dexter library
        Dexter.withActivity(this)
                .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        mRequestingLocationUpdates = true;
                        startLocationUpdates();
                    }
                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response)
                    {
                        if (response.isPermanentlyDenied())
                        {
                            // open device settings when the permission is
                            // denied permanently
                            openSettings();
                        }
                    }
                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token)
                    {
                        token.continuePermissionRequest();
                    }
                }).check();
    }
    private void init()
    {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult)
            {
                super.onLocationResult(locationResult);
                // location is received
                mCurrentLocation = locationResult.getLastLocation();
                mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
                updateLocationUI();
            }
        };

        mRequestingLocationUpdates = false;
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        mLocationSettingsRequest = builder.build();
    }
    /**
     * Restoring values from saved instance state
     */
    private void restoreValuesFromBundle(Bundle savedInstanceState)
    {
        if (savedInstanceState != null)
        {
            if (savedInstanceState.containsKey("is_requesting_updates")) {
                mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates");
            }
            if (savedInstanceState.containsKey("last_known_location")) {
                mCurrentLocation = savedInstanceState.getParcelable("last_known_location");
            }
            if (savedInstanceState.containsKey("last_updated_on")) {
                mLastUpdateTime = savedInstanceState.getString("last_updated_on");
            }
        }
        updateLocationUI();
    }
    /**
     * Update the UI displaying the location data
     * and toggling the buttons
     */
    private void updateLocationUI()
    {
        if (mCurrentLocation != null)
        {
            lat     =   mCurrentLocation.getLatitude();
            longi   =   mCurrentLocation.getLongitude();
            // editTextFirmName.setText("Lat: " + mCurrentLocation.getLatitude() + ", " +"Lng: " + mCurrentLocation.getLongitude()  );

            // giving a blink animation on TextView
            // editTextFirmName.setAlpha(0);
            //  editTextFirmName.animate().alpha(1).setDuration(300);

            // location last updated time
            //    editTextContactName.setText("Last updated on: " + mLastUpdateTime);
        }
    }
    /**
     * Starting location updates
     * Check whether location settings are satisfied and then
     * location updates will be requested
     */

    private void startLocationUpdates()
    {
        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse)
                    {
                        Log.i("LOC", "All location settings are satisfied.");
                        //    Toast.makeText(getApplicationContext(), "Started location updates!", Toast.LENGTH_SHORT).show();
                        //noinspection MissingPermission
                        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                        updateLocationUI();
                    }
                })
                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e)
                    {
                        int statusCode = ((ApiException) e).getStatusCode();
                        switch (statusCode)
                        {
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                Log.i("LOCATION", "Location settings are not satisfied. Attempting to upgrade " +
                                        "location settings ");
                                try
                                {
                                    // Show the dialog by calling startResolutionForResult(), and check the
                                    // result in onActivityResult().
                                    ResolvableApiException rae = (ResolvableApiException) e;
                                    rae.startResolutionForResult(UserDoneComplaintActivity.this, REQUEST_CHECK_SETTINGS);
                                }
                                catch (IntentSender.SendIntentException sie)
                                {
                                    Log.i("LOCATION", "Pending Intent unable to execute request.");
                                }
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                String errorMessage = "Location settings are inadequate, and cannot be fixed here. Fix in Settings.";
                                Log.e("LOCATION", errorMessage);
                                Toast.makeText(UserDoneComplaintActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                        }
                        updateLocationUI();
                    }
                });
    }
    private void openSettings()
    {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
        intent.setData(uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void stopLocationUpdates()
    {
        // Removing location updates
        mFusedLocationClient
                .removeLocationUpdates(mLocationCallback)
                .addOnCompleteListener(this, new OnCompleteListener<Void>()
                {
                    @Override
                    public void onComplete(@NonNull Task<Void> task)
                    {
                        //  Toast.makeText(getApplicationContext(), "Location updates stopped!", Toast.LENGTH_SHORT).show();
                    }
                });
    }
    private boolean checkPermissions()
    {
        int permissionState = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION);
        return permissionState == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (mRequestingLocationUpdates)
        {
            // pausing location updates
            stopLocationUpdates();
        }
    }
    public static String checkDigit(int number)
    {
        return number <= 9 ? "0" + number : String.valueOf(number);
    }
}
