package com.groupr.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.groupr.controller.CreateEventController;
import com.groupr.util.NearbyEvent;
import com.groupr.util.OnNearbyEventListener;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class CreateEventActivity extends FragmentActivity
        implements OnNearbyEventListener {

    private String mUserId;
    private CreateEventActivity mActivity;

    private EditText mNameEditText;
    private TextView mDateTextView;
    private TextView mTimeTextView;
    private EditText mLocationEditText;
    private Button mLocationButton;
    private Button mInviteFriendsButton;
    private Button mEventsButton;

    private RelativeLayout mMainLayout;
    private FrameLayout mProgressLayout;

    private CreateEventController mController;
    private static Place mPlace;

    public static class Extras {
        public static final String USER_ID = "user_id";
    }

    public static void startActivity(Context context, String userId) {
        Intent intent = new Intent(context, CreateEventActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Extras.USER_ID, userId);
        context.startActivity(intent);
    }

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

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setTitle("Create Event");

        mActivity = this;
        mController = new CreateEventController(getApplicationContext(), getResources(),
                AccessToken.getCurrentAccessToken(), null, null);
        mUserId = getIntent().getStringExtra(Extras.USER_ID);

        mNameEditText = (EditText) findViewById(R.id.event_name_edittext);
        mDateTextView = (TextView) findViewById(R.id.event_date_textview);
        mTimeTextView = (TextView) findViewById(R.id.event_time_textview);
        mLocationEditText = (EditText) findViewById(R.id.location_field);
        mLocationButton = (Button) findViewById(R.id.location_button);
        mInviteFriendsButton = (Button) findViewById(R.id.create_event_invite_friends_button);
        mEventsButton = (Button) findViewById(R.id.nearby_events_button);
        mProgressLayout = (FrameLayout) findViewById(R.id.create_event_progress_circle_layout);
        mMainLayout = (RelativeLayout) findViewById(R.id.create_event_main_layout);

        mLocationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mController.launchPlacePicker(mActivity);
            }
        });

        mLocationEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean inFocus) {
                if (inFocus) mLocationButton.performClick();
            }
        });

        mLocationEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLocationButton.performClick();
            }
        });

        final Calendar calendar = Calendar.getInstance();
        final DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        final DateFormat timeFormat = new SimpleDateFormat("hh:mm a");

        mDateTextView.setText(dateFormat.format(calendar.getTime()));
        mDateTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mController.constructDateDialog(mActivity, mDateTextView, dateFormat);
                    }
                });
            }
        });

        mTimeTextView.setText(timeFormat.format(calendar.getTime()));
        mTimeTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mController.constructTimeDialog(mActivity, mTimeTextView);
                    }
                });
            }
        });

        mInviteFriendsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mController.constructInviteFriendsDialog(mActivity, mInviteFriendsButton);
            }
        });

        mEventsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mController.getNearbyEvents(mActivity, mDateTextView.getText().toString(),
                        mPlace, mMainLayout, mProgressLayout);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.create_event_menu_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        int itemId = menuItem.getItemId();

        switch (itemId) {
            case (R.id.save_event_menu_item):
                if (mController.ensureFieldsComplete(mNameEditText.getText().toString(),
                        mLocationEditText.getText().toString())) {
                    try {
                        mController.saveEvent(getContentResolver(), mActivity,
                                mDateTextView.getText().toString(),
                                mTimeTextView.getText().toString(),
                                mNameEditText.getText().toString(),
                                mUserId,
                                mPlace.getName().toString(),
                                mPlace.getLatLng().latitude,
                                mPlace.getLatLng().longitude);
                    } catch (ParseException e) {
                        constructAlertDialog();
                    }
                    return true;
                } else {
                    constructAlertDialog();
                    return true;
                }
            default:
                return super.onOptionsItemSelected(menuItem);
        }
    }

    @Override
    public void onEventSelected(final NearbyEvent event) {
        mNameEditText.setText(event.getName());
        mLocationEditText.setText(event.getLocationName());
        mPlace = new Place() {
            @Override
            public String getId() {
                return null;
            }

            @Override
            public List<Integer> getPlaceTypes() {
                return null;
            }

            @Override
            public CharSequence getAddress() {
                return null;
            }

            @Override
            public Locale getLocale() {
                return null;
            }

            @Override
            public CharSequence getName() {
                return event.getLocationName();
            }

            @Override
            public LatLng getLatLng() {
                return new LatLng(event.getLatitude(), event.getLongitude());
            }

            @Override
            public LatLngBounds getViewport() {
                return null;
            }

            @Override
            public Uri getWebsiteUri() {
                return null;
            }

            @Override
            public CharSequence getPhoneNumber() {
                return null;
            }

            @Override
            public float getRating() {
                return 0;
            }

            @Override
            public int getPriceLevel() {
                return 0;
            }

            @Override
            public Place freeze() {
                return null;
            }

            @Override
            public boolean isDataValid() {
                return false;
            }
        };
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == mController.PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                Place place = PlacePicker.getPlace(data, this);
                if (place != null) {
                    mPlace = place;
                    mLocationEditText.setText(place.getName());
                }
            }
        }
    }

    private void constructAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.event_incomplete_title))
                .setMessage(getString(R.string.event_incomplete_message))
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create().show();
    }
}
