package com.droideve.apps.dealify.activities;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
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.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
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 androidx.core.content.res.ResourcesCompat;

import com.balysv.materialripple.MaterialRippleLayout;
import com.droideve.apps.dealify.location.DirectionPointerLinster;
import com.droideve.apps.dealify.location.GPStracker;
import com.droideve.apps.dealify.location.GetPathFromLocation;
import com.droideve.apps.dealify.location.GoogleDirection;
import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.classes.Discussion;
import com.droideve.apps.dealify.classes.Driver;
import com.droideve.apps.dealify.controllers.SettingsController;
import com.droideve.apps.dealify.controllers.sessions.SessionsController;
import com.droideve.apps.dealify.utils.MapsUtils;
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.PolylineOptions;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import org.w3c.dom.Document;

import java.util.HashMap;
import java.util.Timer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

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

public class FindMyPlaceActivity extends GlobalActivity implements OnMapReadyCallback {

    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_description)
    TextView toolbarDescription;

    @BindView(R.id.btn_open_outside)
    MaterialRippleLayout openOutside;

    @BindView(R.id.btn_contact)
    AppCompatButton btn_contact;

    @BindView(R.id.closeLayout)
    ImageView closeLayout;

    @BindView(R.id.item_focus_layout)
    LinearLayout item_focus_layout;

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.address)
    TextView address;


    Timer timer;
    private GoogleMap mMap;
    private GoogleDirection gd;
    private HashMap<String, String> params;
    private LatLng myPosition, destination;
    private int delivery_id;

    private DatabaseReference mDatabase;

    private final String TAG = "TrackerMapsActivity";
    private final float DEFAULT_ZOOM = 15;


    // click listener
    @OnClick(R.id.btn_contact)
    public void contact(View view) {
        showBottomSheetDialog();
    }

    @OnClick(R.id.btn_open_outside)
    public void submit(View view) {
        showBottomSheetDialog(Double.valueOf(params.get("latitude")), Double.valueOf(params.get("longitude")));
    }


    @OnClick(R.id.closeLayout)
    public void closeLocationDetail(View view) {
        item_focus_layout.setVisibility(View.GONE);
    }

    /**
     * Saves the state of the map when the activity is paused.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_find_my_place);

        ButterKnife.bind(this);

        initToolbar();

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

        delivery_id = SessionsController.getSession().getUser().getId();

        if (getIntent() != null && getIntent().hasExtra("params")) {
            params = (HashMap<String, String>) getIntent().getSerializableExtra("params");
            destination = new LatLng(Double.valueOf(params.get("latitude")), Double.valueOf(params.get("longitude")));

        } else {
            Toast.makeText(this, getString(R.string.error_try_later), Toast.LENGTH_SHORT).show();
            finish();
        }


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

        gd = new GoogleDirection(this);

        // 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);

        // configureCameraIdle();

    }


    private void showBottomSheetDialog(final double latitude, final double longitude) {

        FrameLayout bottom_sheet = findViewById(R.id.bottom_sheet);
        bottom_sheet.setVisibility(View.VISIBLE);

        final BottomSheetBehavior[] mBehavior = {BottomSheetBehavior.from(bottom_sheet)};
        final BottomSheetDialog[] mBottomSheetDialog = {new BottomSheetDialog(this)};

        if (mBehavior[0].getState() == BottomSheetBehavior.STATE_EXPANDED) {
            mBehavior[0].setState(BottomSheetBehavior.STATE_COLLAPSED);
        }

        final View[] view = {getLayoutInflater().inflate(R.layout.order_location_sheet, null)};
        ((AppCompatButton) (view[0].findViewById(R.id.btn_call_client))).setText("Waze");
        //action qte buttons
        (view[0].findViewById(R.id.btn_call_client)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWazeNavigationToB(latitude, longitude);

                mBottomSheetDialog[0].dismiss();
            }
        });


        ((AppCompatButton) (view[0].findViewById(R.id.btn_call_owner))).setText("Google Maps");
        (view[0].findViewById(R.id.btn_call_owner)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGoogleMapsNavigationToB(latitude, longitude);

                mBottomSheetDialog[0].dismiss();
            }
        });

        mBottomSheetDialog[0].setContentView(view[0]);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBottomSheetDialog[0].getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        mBottomSheetDialog[0].show();
        mBottomSheetDialog[0].setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mBottomSheetDialog[0] = null;
            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }


    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.find_my_place);

    }

    private void locationChanged(GoogleMap _mMap) {

        //my position tracker
        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.setMyLocationEnabled(true);

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                Driver user = new Driver(delivery_id,location.getLatitude(), location.getLongitude());
                Log.e(TAG, user.toString());
                if (location.getLongitude() != destination.latitude || location.getLatitude() != destination.latitude) {
                    destination = new LatLng(location.getLatitude(), location.getLongitude());
                    mDatabase.child("users").child("user-" + delivery_id).setValue(user);
                }
            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub
                Log.e(TAG, "onProviderDisabled");

            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub
                Log.e(TAG, "onProviderEnabled");

            }

            @Override
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
                Log.e(TAG, "onStatusChanged");
                // TODO Auto-generated method stub
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        //mMap.setOnCameraIdleListener(onCameraIdleListener);


        if (mMap != null) {

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

            //listener on location changed
            locationChanged(mMap);


            //add destination marker
            Marker marker;
            String promo = null;
            marker = mMap.addMarker(
                    MapsUtils.generateMarker(FindMyPlaceActivity.this,
                            params.get("discussion_id"),
                            destination,
                            null,
                            promo
                    ).draggable(false)

            );
            marker.setTag(Integer.valueOf(params.get("discussion_id")));
            MapsUtils.addMarker(params.get("discussion_id"), marker);


            try {
                gd = new GoogleDirection(this);

                gd.setOnDirectionResponseListener(new GoogleDirection.OnDirectionResponseListener() {

                    @Override
                    public void onResponse(String status, Document doc, GoogleDirection gd) {
                        new GetPathFromLocation(myPosition, destination, new DirectionPointerLinster() {
                            @Override
                            public void onPath(PolylineOptions polyLine) {
                                mMap.addPolyline(polyLine);
                            }
                        }, getResources().getString(R.string.map_direction_api_key),
                                ResourcesCompat.getColor(getApplicationContext().getResources(), R.color.colorAccent, null)).execute();
                    }
                });


                gd.setLogging(true);
                gd.request(myPosition, destination, GoogleDirection.MODE_DRIVING);

            } catch (Exception e) {
                if (APP_DEBUG)
                    e.printStackTrace();
            }




        }


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

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

            setResult(Activity.RESULT_CANCELED, intent);
            finish();
            overridePendingTransition(R.anim.righttoleft_enter, R.anim.righttoleft_exit);
        }

        return super.onOptionsItemSelected(item);
    }


    private void showBottomSheetDialog() {

        FrameLayout bottom_sheet = findViewById(R.id.bottom_sheet);
        bottom_sheet.setVisibility(View.VISIBLE);

        final BottomSheetBehavior[] mBehavior = {BottomSheetBehavior.from(bottom_sheet)};
        final BottomSheetDialog[] mBottomSheetDialog = {new BottomSheetDialog(this)};

        if (mBehavior[0].getState() == BottomSheetBehavior.STATE_EXPANDED) {
            mBehavior[0].setState(BottomSheetBehavior.STATE_COLLAPSED);
        }

        final View[] view = {getLayoutInflater().inflate(R.layout.order_location_sheet, null)};


        ((TextView) (view[0].findViewById(R.id.btn_call_client))).setText(getString(R.string.call));
        (view[0].findViewById(R.id.btn_call_client)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + params.get("phone_number").trim()));
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                    String[] permission = new String[]{Manifest.permission.CALL_PHONE};
                    SettingsController.requestPermissionM(FindMyPlaceActivity.this, permission);
                    return;
                }
                startActivity(intent);

                mBottomSheetDialog[0].dismiss();
            }
        });

        ((TextView) (view[0].findViewById(R.id.btn_call_owner))).setText(getString(R.string.chat));
        (view[0].findViewById(R.id.btn_call_owner)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FindMyPlaceActivity.this, MessengerActivity.class);
                intent.putExtra("type", Discussion.DISCUSION_WITH_USER);
                intent.putExtra("userId", Integer.valueOf(params.get("discussion_id")));
                intent.putExtra("storeName", String.valueOf(params.get("receiver")));
                startActivity(intent);

                mBottomSheetDialog[0].dismiss();
            }
        });

        mBottomSheetDialog[0].setContentView(view[0]);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBottomSheetDialog[0].getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        mBottomSheetDialog[0].show();
        mBottomSheetDialog[0].setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mBottomSheetDialog[0] = null;
            }
        });
    }

    private void openGoogleMapsNavigationToB(double latitude, double longitude) {
        String googleMapsUrl = "google.navigation:q=" + latitude + "," + longitude;
        Uri uri = Uri.parse(googleMapsUrl);

        Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
        mapIntent.setPackage("com.google.android.apps.maps");
        if (mapIntent.resolveActivity(getPackageManager()) != null) {
            startActivity(mapIntent);
        }
    }

    private void openWazeNavigationToB(double latitude, double longitude) {

        try {
            // Launch Waze to look for Hawaii:

            String googleMapsUrl = "waze://?ll=" + latitude + "," + longitude + "&navigate=yes";
            Uri uri = Uri.parse(googleMapsUrl);
            //String url = "https://waze.com/ul?ll=40.761043,-73.980545&navigate=yes";
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            // If Waze is not installed, open it in Google Play:
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.waze"));
            startActivity(intent);
        }
    }


}