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.utils.Constants;
import de.beyondsoft.ownchat.utils.ui.GlideApp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
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.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.load.engine.DiskCacheStrategy;

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(de.beyondsoft.ownchat.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(de.beyondsoft.ownchat.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 loadSearchResult(String newText) {
        if(mGroup != null && newText != null) {
            mCallback.searchMessagesFromDBByGroupIdAndText(mGroup.id, newText);
        }
    }

    @Override
    protected void loadMessages() {
        if(!TextUtils.isEmpty(mGroup.mobile)) {
            mExtraImageView.setVisibility(View.VISIBLE);
            mExtraImageView.setImageResource(de.beyondsoft.ownchat.R.drawable.call);
        }

        if(mSystemUtils.isNetworkUnavailable()) {
            mCallback.loadMessagesFromDBByGroupId(mGroup.id, true);
            showError(de.beyondsoft.ownchat.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.onlyEmployees ? de.beyondsoft.ownchat.R.color.colorBlack : de.beyondsoft.ownchat.R.color.colorHelpGroup));

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

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

        Drawable drawable = mExtraImageView.getDrawable();

        if(drawable == null) {
            ViewGroup.LayoutParams layoutParams = mExtraImageView.getLayoutParams();
            layoutParams.width = 0;
            mExtraImageView.setLayoutParams(layoutParams);
        }

        if(TextUtils.isEmpty(mGroup.avatar)) {
            mChatImageView.setImageResource(mGroup.onlyEmployees ? de.beyondsoft.ownchat.R.drawable.avatar : R.drawable.avatar_help);
        } else {
            GlideApp.with(this)
                    .asBitmap()
                    .load(mGroup.avatar)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .placeholder(R.drawable.avatar)
                    .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);
            }
        }
    };

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