package de.beyondsoft.ownchat.page.contacts;

import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.data.AppPrefsConstants;
import de.beyondsoft.ownchat.data.events.GroupUpdatedEvent;
import de.beyondsoft.ownchat.data.prefs.BooleanPreference;
import de.beyondsoft.ownchat.data.prefs.LongPreference;
import de.beyondsoft.ownchat.data.prefs.StringPreference;
import de.beyondsoft.ownchat.di.InjectionHelper;
import de.beyondsoft.ownchat.model.Group;
import de.beyondsoft.ownchat.model.Message;
import de.beyondsoft.ownchat.page.chat.GroupChatActivity;
import de.beyondsoft.ownchat.page.chat.SingleChatActivity;
import de.beyondsoft.ownchat.page.common.BaseFragment;
import de.beyondsoft.ownchat.page.sharing.SharingActivity;
import de.beyondsoft.ownchat.utils.Constants;
import de.beyondsoft.ownchat.utils.ui.EmptyLayout;
import de.beyondsoft.ownchat.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;

    @Inject
    @Named(AppPrefsConstants.IS_COMING_FROM_SHARING_ACTIVITY)
    BooleanPreference mIsComingFromSharingActivity;

    @Inject
    @Named(AppPrefsConstants.PATH_TO_FILE_TO_SHARE)
    StringPreference mSelectedFilePath;

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

        if(mIsComingFromSharingActivity.get() && mSelectedFilePath.get() != null) {
            startActivity(new Intent(getActivity(), SharingActivity.class));
        }
    }

    @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);
        }
    };
}