package com.sliit.smartserviceassistant;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.graphics.Color;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{

    private GoogleMap mMap;
    FusedLocationProviderClient client;
    SupportMapFragment supportMapFragment;
    Button btFind;
    double currentLat =0, currentLong = 0;

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

        btFind=findViewById(R.id.btnRestaurant);


        btFind.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


                System.out.println(currentLat);
                System.out.println(currentLong);
                float radius=10;
                float lon= (float) currentLong;
                float lat= (float) currentLat;

                Retrofit retrofit4 = new Retrofit.Builder()
                        .baseUrl("http://192.168.1.5:8000/api/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();




                RetrofitAPI4 retrofitAPI4 = retrofit4.create(RetrofitAPI4.class);

                DataModal4 modal4 = new DataModal4(lon,lat,radius);


                Call<DataModal4> call4 = retrofitAPI4.createPost4(modal4);

                call4.enqueue(new Callback<DataModal4>() {

                    @Override
                    public void onResponse(Call<DataModal4> call4, Response<DataModal4> response4) {
                        ArrayList reponding=response4.body().response;

                        for (int i = 0; i <reponding.size() ; i++) {
                            ArrayList reponding1= (ArrayList) reponding.get(i);

                            double lati= (double) reponding1.get(0);
                            double longi=(double) reponding1.get(1);
                            String place=(String) reponding1.get(2);



                            supportMapFragment.getMapAsync(new OnMapReadyCallback() {
                                @Override
                                public void onMapReady(@NonNull GoogleMap googleMap) {
                                    LatLng latLng=new LatLng(longi
                                            ,lati);
                                    MarkerOptions options=new MarkerOptions().position(latLng)
                                            .title(place);
                                    //googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,100));
                                    googleMap.addMarker(options);




                                }
                            });

                            System.out.println("latitude"+lati);
                            System.out.println("longtiude"+longi);


                       }


                        System.out.println( reponding.size());

                    Toast.makeText(MapsActivity.this, "Data can added", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onFailure(Call<DataModal4> call4, Throwable t) {

                    Toast.makeText(MapsActivity.this, "Data can't added", Toast.LENGTH_SHORT).show();
                    System.out.println(t.getMessage());

                }
            });


        }
        });

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        supportMapFragment  = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        client = LocationServices.getFusedLocationProviderClient(this);
        if (ActivityCompat.checkSelfPermission(MapsActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            getCurrentLocation();
        }else{
            ActivityCompat.requestPermissions(MapsActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},44) ;
        }

        //mapFragment.getMapAsync(this);
    }


    public void getCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions

            return;
        }
        Task<Location> task = client.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if(location !=null){
                    currentLat =location.getLatitude();
                    currentLong=location.getLongitude();
                    System.out.println(currentLat);
                    System.out.println(currentLong);
                    supportMapFragment.getMapAsync(new OnMapReadyCallback() {
                        @Override
                        public void onMapReady(@NonNull GoogleMap googleMap) {
                            LatLng latLng=new LatLng(location.getLatitude()
                                    ,location.getLongitude());
                            MarkerOptions options=new MarkerOptions().position(latLng)
                                    .title("My Current Location")
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
                            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
                            Circle circle =  googleMap.addCircle(new CircleOptions()
                                    .center(new LatLng(currentLat, currentLong))
                                    .radius(6900)
                                    .strokeColor(Color.BLUE)
                                    .fillColor(Color.TRANSPARENT));

                            googleMap.addMarker(options);




                        }
                    });
                }
            }
        });
    }

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

        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }



}