package com.pixelnx.localhelp.ui.mapaddress;

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.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.pm.PackageManager;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import android.os.Bundle;


import android.view.View;
import android.widget.LinearLayout;


import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.MarkerOptions;
import com.pixelnx.localhelp.R;

import com.pixelnx.localhelp.utils.widgets.CustomButton;


import java.util.Objects;


public class ActivityMapAddress extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener,LocationListener,GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {


    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private SupportMapFragment mapFragment;
    CustomButton btOK;
    CustomButton btCancel;
    private LinearLayout rlDialog;
      Context context;
    private Double latitude;
    private Double  longitude;

    FusedLocationProviderClient fusedLocationProviderClient;
    LocationRequest mLocationRequest;
    private static final long INTERVAL = 5000;
    private static final long FASTEST_INTERVAL = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context =ActivityMapAddress.this;
createLocationRequest();

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.address)
                    .setMessage(R.string.address_dil)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {


                            setContentView(R.layout.activity_map_address);
                            checkLocationPermission();

                            initial();
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create()
                    .show();
        }else{
            LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        Objects.requireNonNull(service).requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, (LocationListener) this);
            setContentView(R.layout.activity_map_address);
            checkLocationPermission();

            initial();

        }


    }



    private void initial() {

        rlDialog = findViewById(R.id.rlDialog);
        btCancel = findViewById(R.id.btCancel);
        btOK = findViewById(R.id.btOK);


        btOK.setOnClickListener(this);
        btCancel.setOnClickListener(this);
    }


    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {


            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {


                new AlertDialog.Builder(this)
                        .setTitle(R.string.title_location_permission)
                        .setMessage(R.string.text_location_permission)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {


                                ActivityCompat.requestPermissions(ActivityMapAddress.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);


                            }
                        })
                        .create()
                        .show();


            } else {

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
            Objects.requireNonNull(service).requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, (LocationListener) this);
            mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);

            assert mapFragment != null;
            mapFragment.getMapAsync(this);


            return true;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_LOCATION) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
                    Objects.requireNonNull(service).requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 , 0, (LocationListener) this);
                    mapFragment = (SupportMapFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.map);

                    assert mapFragment != null;
                    mapFragment.getMapAsync(this);


                }

            }

        }
    }




    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }


    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(final GoogleMap googleMap) {


        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        Objects.requireNonNull(service).requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);



        @SuppressLint("MissingPermission") Location location = service.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());





            googleMap.addMarker(new MarkerOptions().position(userLocation)
                    .title("Your location in map "));
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
            latitude = userLocation.latitude;
            longitude = userLocation.longitude;
            rlDialog.setVisibility(View.VISIBLE);
            Intent returnIntent = new Intent();

            returnIntent.putExtra("city", "" + latitude + "," + longitude);
            returnIntent.putExtra("lati", "" + latitude);
            returnIntent.putExtra("long", "" + longitude);

            setResult(Activity.RESULT_OK, returnIntent);
            finish();

        }else{

            service.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, (LocationListener) this);





        }


        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng latLng) {


                MarkerOptions markerOptions = new MarkerOptions();


                markerOptions.position(latLng);

                markerOptions.title(latLng.latitude + " : " + latLng.longitude);
                latitude = latLng.latitude;
                longitude = latLng.longitude;

                googleMap.clear();


                googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));


                googleMap.addMarker(markerOptions);

                rlDialog.setVisibility(View.VISIBLE);


            }
        });

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btOK) {
            Intent returnIntent = new Intent();

            returnIntent.putExtra("city", "" + latitude + "," + longitude);
            returnIntent.putExtra("lati", "" + latitude);
            returnIntent.putExtra("long", "" + longitude);

            setResult(Activity.RESULT_OK, returnIntent);
            finish();
        } else if (id == R.id.btCancel) {
            Intent re = new Intent();
            re.putExtra("city", "");
            setResult(Activity.RESULT_CANCELED, re);
            finish();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        throw new UnsupportedOperationException();


    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onProviderEnabled(String s) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onProviderDisabled(String s) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onConnectionSuspended(int i) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        throw new UnsupportedOperationException();
    }
}
