package com.droideve.apps.dealify.activities;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.droideve.apps.dealify.AppController;
import com.droideve.apps.dealify.location.GPStracker;
import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Driver;
import com.droideve.apps.dealify.classes.User;
import com.droideve.apps.dealify.controllers.SettingsController;
import com.droideve.apps.dealify.helper.CommunFunctions;
import com.droideve.apps.dealify.network.ServiceHandler;
import com.droideve.apps.dealify.network.VolleySingleton;
import com.droideve.apps.dealify.network.api_request.SimpleRequest;
import com.droideve.apps.dealify.parser.api_parser.UserParser;
import com.droideve.apps.dealify.utils.NSToast;
import com.droideve.apps.dealify.utils.Utils;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.RealmList;

import static com.droideve.apps.dealify.appconfig.AppConfig.APP_DEBUG;

public class DeliveryTrackingActivity extends GlobalActivity implements OnMapReadyCallback {

    private final String TAG = "DeliveryTrackingActivity";
    private final int order_id = -1;
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarDescription;
    @BindView(R.id.item_focus_layout)
    LinearLayout item_focus_layout;
    @BindView(R.id.btn_contact)
    AppCompatButton btn_contact;
    @BindView(R.id.closeLayout)
    ImageView closeLayout;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.address)
    TextView address;
    //add destination marker
    Marker marker;

    User mDriver = null;
    private GoogleMap mMap;
    private DatabaseReference mDatabase;
    private HashMap<String, String> params;
    private LatLng myPosition, delivery_boy;
    private int delievry_boy_id = -1;


    // click listener
    @OnClick(R.id.btn_contact)
    public void contact(View view) {
        if (mDriver != null && mDriver.getPhone() != null) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + mDriver.getPhone().trim()));
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                String[] permission = new String[]{Manifest.permission.CALL_PHONE};
                SettingsController.requestPermissionM(DeliveryTrackingActivity.this, permission);
                return;
            }
            startActivity(intent);
        } else {
            NSToast.show(( getString(R.string.driver_detail_not_found)));

        }

    }


    // click listener
    @OnClick(R.id.closeLayout)
    public void closeDetailLayout(View view) {
        if (item_focus_layout.isShown())
            com.droideve.apps.dealify.animation
                    .Animation.hideWithZoomEffect(item_focus_layout);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_boy_tracking);
        ButterKnife.bind(this);

        initToolbar();

        // init firebase database
        mDatabase = FirebaseDatabase.getInstance().getReference();

        //INITIALIZE MY LOCATION
        GPStracker trackMe = new GPStracker(this);
        myPosition = new LatLng(trackMe.getLatitude(), trackMe.getLongitude());


        if (getIntent() != null && getIntent().hasExtra("params")) {
            params = (HashMap<String, String>) getIntent().getSerializableExtra("params");
            delievry_boy_id = Integer.valueOf(params.get("delivery_id"));

            //retrieve driver detail from the server
            if (delievry_boy_id > 0)
                getDriverDetail(delievry_boy_id);

        } else {
            NSToast.show(( getString(R.string.error_try_later)));
            finish();
        }


        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


    }

    public void initToolbar() {

        toolbar = findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbarDescription.setVisibility(View.GONE);
        toolbarTitle.setText(R.string.order_tracking);

    }


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

        //mMap.setOnCameraIdleListener(onCameraIdleListener);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 15));
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                item_focus_layout.setVisibility(View.VISIBLE);
                return false;
            }
        });


        checkDeliveryBoyLocation(mMap);


        mMap.setMyLocationEnabled(true);
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng point) {
                mMap.clear();

                //mMap.addMarker(new MarkerOptions().position(point).title("My location").draggable(true));
            }
        });

    }


    public void getDriverDetail(int driver_id) {


        RequestQueue queue = VolleySingleton.getInstance(this).getRequestQueue();

        SimpleRequest request = new SimpleRequest(Request.Method.POST,
                Constances.API.API_GET_USERS, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {

                    JSONObject jsonObject = new JSONObject(response);

                    final UserParser mUsersParser = new UserParser(jsonObject);
                    RealmList<User> list = mUsersParser.getUser();
                    if (list.size() > 0)
                        mDriver = list.get(0);

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

                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (APP_DEBUG) {
                    Log.e("ERROR", error.toString());
                }
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", Utils.getToken(AppController.getInstance()));
                params.put("mac_adr", ServiceHandler.getMacAddr());
                params.put("limit", "1");
                params.put("page", "1");
                params.put("uid", driver_id + "");

                return params;
            }

        };

        request.setRetryPolicy(new DefaultRetryPolicy(SimpleRequest.TIME_OUT,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        queue.add(request);


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (android.R.id.home == item.getItemId()) {
            Intent intent = new Intent();

            setResult(Activity.RESULT_CANCELED, intent);
            finish();
            
        }

        return super.onOptionsItemSelected(item);
    }


    private void checkDeliveryBoyLocation(GoogleMap _mMap) {
        // [START post_value_event_listener]
        ValueEventListener postListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get Post object and use the values to update the UI

                Driver driver = dataSnapshot.child("users").child("user-" + delievry_boy_id).getValue(Driver.class);
                //Driver driver = dataSnapshot.getValue(Driver.class);
                if (driver != null) {
                    if (delivery_boy != null && (delivery_boy.latitude == driver.lat && driver.lng == delivery_boy.longitude)) {

                    } else {
                        delivery_boy = new LatLng(driver.lat, driver.lng);

                        _mMap.clear();

                        _mMap.addMarker(new MarkerOptions().position(delivery_boy).title(mDriver != null ? mDriver.getUsername() : getString(R.string.delivery_boy))
                                // below line is use to add custom marker on our map.
                                .icon(CommunFunctions.BitmapFromVector(R.drawable.delivery_marker)));

                        _mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(delivery_boy, 18));


                    }

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w("DeliveryTracking", "loadPost:onCancelled", databaseError.toException());
            }
        };

        //add value event changed listener
        mDatabase.addValueEventListener(postListener);

    }


}