package de.beyondsoft.ownchat.page.chat;

import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.model.Group;
import de.beyondsoft.ownchat.model.Message;
import de.beyondsoft.ownchat.page.chatmembers.ChatMembersActivity;
import de.beyondsoft.ownchat.utils.Constants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;

public class GroupChatActivity extends BaseChatActivity {

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getBundleExtra(Constants.MESSAGE);

            if(mCallback == null) {
                mChatPresenter.attachView(GroupChatActivity.this);
            }

            if(mCallback.getGroupId() == bundle.getLong(Constants.GROUP_ID)) {
                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,
                        true,
                        mUserIdPreference.get(),
                        false);

                mCallback.saveMessage(message);
                Bundle results = getResultExtras(true);
                results.putBoolean(Constants.CHAT_IS_ALREADY_OPEN, true);
            }
        }
    };

    public static Intent createIntent(Context context, Group group) {
        Intent intent = new Intent(context, GroupChatActivity.class);
        intent.putExtra(GROUP_ARG, group);
        return intent;
    }

    public static Intent createIntent(Context context, Bundle bundle) {
        Intent intent = new Intent(context, GroupChatActivity.class);
        intent.putExtra(MESSAGE_ARG, bundle);
        return intent;
    }

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

        mChatPresenter.attachView(this);
        mCallback.resetMessages();

        if(getIntent().hasExtra(MESSAGE_ARG)) {
            Bundle bundle = getIntent().getBundleExtra(MESSAGE_ARG);
            long groupId = bundle.getLong(Constants.GROUP_ID);

            if(mSystemUtils.isNetworkUnavailable()) {
                mCallback.loadMessagesFromDBByGroupId(groupId, true);
                showError(R.string.error_no_internet_connection);
            } else {
                mCallback.loadMessagesFromServerByGroupId(groupId);
            }

            mCallback.findGroupById();
        } else {
            setGroupFromArguments();
        }
    }

    @Override
    protected void onResume() {
        if(!mChatPresenter.isAttached()) {
            mChatPresenter.attachView(this);
            mBaseChatAdapter.resetItemsProgress();

            if(mSystemUtils.isNetworkUnavailable()) {
                mCallback.loadMessagesFromDBByGroupId(mGroup.id, true);
                showError(R.string.error_no_internet_connection);
            } else {
                if(mGroup == null) {
                    if(getIntent().hasExtra(MESSAGE_ARG)) {
                        long groupId = getIntent().getBundleExtra(MESSAGE_ARG).getLong(Constants.GROUP_ID);

                        mCallback.findGroupById();

                        mCallback.fetchNewMessages(groupId);
                        super.onResume();
                        return;
                    }

                    setGroupFromArguments();
                    mCallback.fetchNewMessages(mGroup.id);
                } else {
                    mCallback.fetchNewMessages(mGroup.id);
                }
            }
        }

        cancelNotification();
        IntentFilter filter = new IntentFilter(Constants.NOTIFICATION_BROADCAST);
        registerReceiver(mReceiver, filter);

        super.onResume();
    }

    @Override
    protected void loadSearchResult(String newText) {
        if(mGroup != null && newText != null) {
            mCallback.searchMessagesFromDBByGroupIdAndText(mGroup.id, newText);
        }
    }

    @Override
    protected void loadMessages() {
        if(mSystemUtils.isNetworkUnavailable()) {
            mCallback.loadMessagesFromDBByGroupId(mGroup.id, true);
            showError(R.string.error_no_internet_connection);
        } else {
            if(mGroup != null) {
                mCallback.loadMessagesFromServerByGroupId(mGroup.id);
            }
        }
    }

    @Override
    protected void setToolbar() {
        mSingleChatTitleTextView.setVisibility(View.GONE);

        mGroupTitleTextView.setVisibility(View.VISIBLE);

        mGroupMembersTextView.setVisibility(View.VISIBLE);

        mExtraImageView.setVisibility(View.VISIBLE);

        mGroupMembersTextView.setText(mGroup.getContactsNames());

        mExtraImageView.setImageResource(R.drawable.vertical_dots);

        mChatImageView.setImageResource(mGroup.isHelpGroup() ? R.drawable.avatar_help_group : R.drawable.avatar_team_group);

        mChatSearchView.setOnQueryTextListener(this);
        mChatSearchView.setOnSearchClickListener(view -> {
            mGroupMembersTextView.setVisibility(View.INVISIBLE);
            mGroupTitleTextView.setVisibility(View.INVISIBLE);
            mChatImageView.setVisibility(View.INVISIBLE);
        });

        mChatSearchView.setOnCloseListener(() -> {
            mGroupMembersTextView.setVisibility(View.VISIBLE);
            mGroupTitleTextView.setVisibility(View.VISIBLE);
            mChatImageView.setVisibility(View.VISIBLE);
            return false;
        });

        mGroupTitleTextView.setText(mGroup.name);
        mGroupTitleTextView.setTextColor(ContextCompat.getColor(this, mGroup.isHelpGroup() ? R.color.colorHelpGroup : R.color.colorTeamGroup));
    }

    @Override
    protected void onPause() {
        Log.v("GROUP_NOTIFICATION", "onPause() called");

        mChatPresenter.detachView();

        try {
            unregisterReceiver(mReceiver);
        } catch(Exception e) {
            Log.e(GroupChatActivity.class.getSimpleName(), e.getMessage(), e);
        }

        super.onPause();
    }

    @Override
    protected void extraImageClicked() {
        startActivity(ChatMembersActivity.createIntent(this, mGroup));
    }

    @Override
    protected BaseChatAdapter getAdapter() {
        return new GroupChatAdapter(mUserIdPreference.get());
    }

    @Override
    public void setGroup(Group group) {
        Log.e("GROUP_NOTIFICATION", "Setting group: " + group);

        mGroup = group;
        setToolbar();

        cancelNotification();
    }

    public void closeSearchView() {
        mGroupMembersTextView.setVisibility(View.VISIBLE);
        mGroupTitleTextView.setVisibility(View.VISIBLE);
        mChatImageView.setVisibility(View.VISIBLE);
        mChatSearchView.setIconified(true);
    }
}