package com.p3.bewoplaner.page.chat;

import com.bumptech.glide.Glide;
import com.p3.bewoplaner.R;
import com.p3.bewoplaner.model.Group;
import com.p3.bewoplaner.model.Message;
import com.p3.bewoplaner.utils.Constants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;

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

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

    public static Intent createIntent(Context context, Bundle bundle) {
        Intent intent = new Intent(context, SingleChatActivity.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);
            mGroup = new Group();
            mGroup.id = bundle.getLong(Constants.GROUP_ID);
            mGroup.name = bundle.getString(Constants.USERNAME);
            mGroup.avatar = bundle.getString(Constants.USER_AVATAR);

            if (mSystemUtils.isNetworkUnavailable()) {
                mCallback.loadMessagesFromDBByGroupId(mGroup.id, true);
                showError(R.string.error_no_internet_connection);
            } else {
                mCallback.loadMessagesFromServerByGroupId(mGroup.id);
            }
            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 {
                mCallback.fetchNewMessages(mGroup.id);
            }
        }
        cancelNotification();
        IntentFilter filter = new IntentFilter(Constants.NOTIFICATION_BROADCAST);
        registerReceiver(mReceiver, filter);
        super.onResume();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(mReceiver);
        mChatPresenter.detachView();
        super.onPause();
    }

    @Override
    protected void loadMessages() {
        if (!TextUtils.isEmpty(mGroup.mobile)) {
            mExtraImageView.setVisibility(View.VISIBLE);
            mExtraImageView.setImageResource(R.drawable.call);
        }
        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.VISIBLE);
        mSingleChatTitleTextView.setText(mGroup.name);
        mSingleChatTitleTextView.setTextColor(ContextCompat.getColor(this,
                mGroup.isEmployee(mGroup.users) ? R.color.colorHelpGroup : R.color.colorBlack));
        if (TextUtils.isEmpty(mGroup.avatar)) {
            mChatImageView.setImageResource(R.drawable.avatar);
        } else {
            Glide.with(this).load(mGroup.avatar)
                    .placeholder(R.drawable.avatar)
                    .dontAnimate()
                    .into(mChatImageView);
        }
    }

    @Override
    protected void extraImageClicked() {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel",
                mGroup.mobile,
                null));
        startActivity(intent);
    }

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

    @Override
    public void setGroup(Group groups) {
        mGroup = groups;
        loadMessages();
        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(SingleChatActivity.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);
            }
        }
    };
}