package com.p3.bewoplaner.page.contacts;

import com.p3.bewoplaner.R;
import com.p3.bewoplaner.data.AppPrefsConstants;
import com.p3.bewoplaner.data.events.GroupUpdatedEvent;
import com.p3.bewoplaner.data.prefs.LongPreference;
import com.p3.bewoplaner.di.InjectionHelper;
import com.p3.bewoplaner.model.Group;
import com.p3.bewoplaner.model.Message;
import com.p3.bewoplaner.page.chat.GroupChatActivity;
import com.p3.bewoplaner.page.chat.SingleChatActivity;
import com.p3.bewoplaner.page.common.BaseFragment;
import com.p3.bewoplaner.utils.Constants;
import com.p3.bewoplaner.utils.ui.EmptyLayout;
import com.p3.bewoplaner.utils.ui.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

import javax.inject.Inject;
import javax.inject.Named;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by imarneanu on 2/13/17.
 */
public class ContactsFragment extends BaseFragment
        implements ContactsView, ContactsAdapter.OnOpenClickListener, SearchView.OnQueryTextListener {

    @BindView(R.id.contacts_recycler_view)
    RecyclerView mContactsRecyclerView;

    @BindView(R.id.contacts_empty_layout)
    EmptyLayout mEmptyLayout;

    @BindView(R.id.contacts_coordinator_layout)
    CoordinatorLayout mCoordinatorLayout;

    @BindView(R.id.contacts_swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @Inject
    ContactsPresenter mContactsPresenter;

    @Inject
    @Named(AppPrefsConstants.USER_ID)
    LongPreference mUserIdPreference;

    private Callback mCallback;
    private ContactsAdapter mContactsAdapter;
    private RecyclerView.ItemDecoration mHorizontalDividerItemDecoration;
    private Snackbar mSnackbar;
    private SearchView mSearchView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        InjectionHelper.getContactsComponent(context).inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_contacts, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mUnbinder = ButterKnife.bind(this, view);
        getActivity().setTitle(R.string.title_contacts);
        EventBus.getDefault().register(this);
        mContactsPresenter.attachView(this);
        IntentFilter filter = new IntentFilter(Constants.NOTIFICATION_BROADCAST);
        getActivity().registerReceiver(mReceiver, filter);

        mHorizontalDividerItemDecoration = new HorizontalDividerItemDecoration.Builder(getActivity())
                .colorResId(R.color.colorFill).build();
        mContactsRecyclerView.addItemDecoration(mHorizontalDividerItemDecoration);
        mContactsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        mContactsAdapter = new ContactsAdapter(this, mUserIdPreference.get());
        mContactsRecyclerView.setAdapter(mContactsAdapter);

        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorDefault, R.color.colorDefaultBright);
        mSwipeRefreshLayout.setOnRefreshListener(this::refresh);
    }

    private void refresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        resetSearch();
        mCallback.loadGroups();
    }

    @Override
    public void onResume() {
        super.onResume();
        resetSearch();
        mCallback.loadGroups();
        mCallback.loadGroupsFromDB();
    }

    private void resetSearch() {
        if (mSearchView != null && !mSearchView.isIconified()) {
            mSearchView.setQuery(null, false);
            mSearchView.setIconified(true);
        }
    }

    @Override
    public void showError(@StringRes int message) {
        if (mSnackbar == null) {
            mSnackbar = Snackbar.make(mCoordinatorLayout, message, Snackbar.LENGTH_LONG);
            mSnackbar.setActionTextColor(ContextCompat.getColor(getActivity(), R.color.colorDefault));
        }
        mSnackbar.setText(message);
        mSnackbar.show();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        mContactsAdapter = null;
        mContactsRecyclerView.setAdapter(null);
        mContactsRecyclerView.removeItemDecoration(mHorizontalDividerItemDecoration);
        mSwipeRefreshLayout.setOnRefreshListener(null);
        super.onDestroyView();
        getActivity().unregisterReceiver(mReceiver);
        mContactsPresenter.detachView();
    }

    @Override
    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    @Override
    public void showProgress() {
        mEmptyLayout.showLoading();
    }

    @Override
    public void hideProgress() {
        mEmptyLayout.setVisibility(View.GONE);
    }

    @Override
    public void setGroups(ArrayList<Group> groups) {
        mContactsAdapter.setGroups(groups);
    }

    @Override
    public void onOpenGroupMessage(Group group) {
        if (TextUtils.isEmpty(mSearchView.getQuery())) {
            mSearchView.setIconified(true);
        }
        startActivity(GroupChatActivity.createIntent(getActivity(), group));
    }

    @Override
    public void onOpenPrivateMessage(Group group) {
        startActivity(SingleChatActivity.createIntent(getActivity(), group));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.activity_main_menu, menu);

        MenuItem menuItem = menu.findItem(R.id.action_search);
        mSearchView = (SearchView) menuItem.getActionView();
        mSearchView.setOnQueryTextListener(this);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText)) {
            mCallback.loadGroupsFromDB();
        } else {
            mCallback.loadGroupsContainingName(newText);
        }
        return false;
    }

    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInvalidToken(GroupUpdatedEvent groupUpdatedEvent) {
        if (mCallback == null) {
            mContactsPresenter.attachView(this);
        }
        mCallback.loadGroupsFromDB();
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (mCallback == null) {
                return;
            }
            Bundle bundle = intent.getBundleExtra(Constants.MESSAGE);
            Message message = new Message(bundle.getString(Constants.MESSAGE_ID),
                    bundle.getLong(Constants.GROUP_ID),
                    bundle.getLong(Constants.CREATED_AT),
                    bundle.getString(Constants.MESSAGE_TEXT),
                    bundle.getString(Constants.FILE),
                    bundle.getString(Constants.SMALLER_IMAGE),
                    bundle.getString(Constants.FILENAME),
                    null,
                    bundle.getLong(Constants.USER_ID),
                    bundle.getString(Constants.USERNAME),
                    bundle.getString(Constants.USER_AVATAR),
                    Message.Status.DELIVERED,
                    false,
                    mUserIdPreference.get(),
                    false);
            mCallback.storeGroupLocally(bundle.getLong(Constants.GROUP_ID), message);
        }
    };
}