package com.p3.bewoplaner.page.chat;

import com.p3.bewoplaner.R;
import com.p3.bewoplaner.model.Group;
import com.p3.bewoplaner.model.Message;
import com.p3.bewoplaner.page.chatmembers.ChatMembersActivity;
import com.p3.bewoplaner.utils.Constants;

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.v4.content.ContextCompat;
import android.view.View;

/**
 * Created by Rares Teodorescu on 21/02/2017.
 */
public class GroupChatActivity extends BaseChatActivity {

    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 groupId) {
        Intent intent = new Intent(context, GroupChatActivity.class);
        intent.putExtra(MESSAGE_ARG, groupId);
        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.fetchNewMessages(groupId);
                        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 loadMessages() {
        if (mSystemUtils.isNetworkUnavailable()) {
            mCallback.loadMessagesFromDBByGroupId(mGroup.id, true);
            showError(R.string.error_no_internet_connection);
        } else {
            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);
        mGroupTitleTextView.setText(mGroup.name);
        mGroupTitleTextView.setTextColor(ContextCompat.getColor(this,
                mGroup.isHelpGroup() ? R.color.colorHelpGroup : R.color.colorTeamGroup));
    }

    @Override
    protected void onPause() {
        mChatPresenter.detachView();
        unregisterReceiver(mReceiver);
        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) {
        mGroup = group;
        setToolbar();
    }

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