package de.beyondsoft.ownchat.page.contacts;

import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

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

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.model.Group;
import de.beyondsoft.ownchat.utils.DateUtils;
import de.beyondsoft.ownchat.utils.ui.GlideApp;
import de.beyondsoft.ownchat.utils.ui.ViewUtils;
import de.hdodenhof.circleimageview.CircleImageView;
import hani.momanii.supernova_emoji_library.Helper.EmojiconTextView;

class ContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int GROUP_TYPE = 0;
    private static final int CONTACT_TYPE = 1;

    private ArrayList<Group> mGroups;
    private OnOpenClickListener mItemClickListener;
    private long mUserId;

    interface OnOpenClickListener {
        void onOpenGroupMessage(Group group);

        void onOpenPrivateMessage(Group contact);
    }

    ContactsAdapter(OnOpenClickListener openClickListener, long userId) {
        mItemClickListener = openClickListener;
        mGroups = new ArrayList<>();
        mUserId = userId;
    }

    void setGroups(ArrayList<Group> groups) {
        mGroups.clear();

        if(groups != null) {
            mGroups.addAll(groups);
        }

        notifyDataSetChanged();
    }

    @Override
    public final int getItemViewType(int position) {
        if(mGroups.get(position).users.size() > 2) {
            return GROUP_TYPE;
        }

        return CONTACT_TYPE;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact, parent, false);
        return new ContactViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Group group = mGroups.get(position);
        ContactViewHolder viewHolder = (ContactViewHolder) holder;
        setLastMessage(group, viewHolder);

        int type = getItemViewType(position);

        if(type == GROUP_TYPE) {
            viewHolder.name.setText(group.name);
            viewHolder.name.setTextColor(ContextCompat.getColor(viewHolder.name.getContext(), group.isHelpGroup() ? R.color.colorHelpGroup : R.color.colorTeamGroup));
            viewHolder.avatar.setImageResource(group.isHelpGroup() ? R.drawable.avatar_help_group : R.drawable.avatar_team_group);

            return;
        } else if(!group.onlyEmployees) {
            viewHolder.avatar.setImageResource(R.drawable.avatar_help);
        }

        if(type == CONTACT_TYPE) {
            viewHolder.name.setTextColor(ContextCompat.getColor(viewHolder.name.getContext(), group.isEmployee(mGroups.get(position).users) ? R.color.colorBlack : R.color.colorHelpGroup));
        }

        viewHolder.name.setText(group.name);

        GlideApp.with(viewHolder.avatar.getContext())
                .asBitmap()
                .load(group.avatar)
                .placeholder(group.onlyEmployees ? R.drawable.avatar_list : R.drawable.avatar_help)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(viewHolder.avatar);
    }

    private void setLastMessage(Group group, ContactViewHolder viewHolder) {
        if(group.lastMessage == null) {
            viewHolder.lastMessage.setText(null);
            viewHolder.messageTimestamp.setText(null);
            viewHolder.messageStatus.setImageResource(0);
            return;
        }

        boolean isMessageSentByUser = group.lastMessage.senderId == mUserId;

        if(!group.isRead() && !isMessageSentByUser) {
            viewHolder.lastMessage.setTypeface(null, Typeface.BOLD);
            viewHolder.lastMessage.setTextColor(ContextCompat.getColor(viewHolder.lastMessage.getContext(), R.color.colorDefaultBright));
        } else {
            viewHolder.lastMessage.setTypeface(null);
            viewHolder.lastMessage.setTextColor(ContextCompat.getColor(viewHolder.lastMessage.getContext(), R.color.colorSubtitle));
        }

        viewHolder.lastMessage.setText(TextUtils.isEmpty(group.lastMessage.message) ? group.lastMessage.originalFilename : group.lastMessage.message);
        viewHolder.messageTimestamp.setText(DateUtils.toHourOrDateFormatHour(group.lastMessage.createdAt));

        viewHolder.attachmentIcon.setVisibility(View.GONE);

        if(group.lastMessage != null && group.lastMessage.filePath != null && group.lastMessage.filePath.length() > 0) {
            String fileType = de.beyondsoft.ownchat.utils.FileUtils.getFileTypeFromFilePath(group.lastMessage.filePath);
            String messageText;

            if(fileType.contains("image")) {
                if(fileType.contains("gif")) {
                    viewHolder.attachmentIcon.setImageResource(R.drawable.ic_gif_24px);
                    messageText = viewHolder.lastMessage.getContext().getString(R.string.attachment_gif);
                } else {
                    viewHolder.attachmentIcon.setImageResource(R.drawable.camera_24px);
                    messageText = viewHolder.lastMessage.getContext().getString(R.string.attachment_image);
                }
            } else if(fileType.contains("video")) {
                viewHolder.attachmentIcon.setImageResource(R.drawable.videocam_24px);
                messageText = viewHolder.lastMessage.getContext().getString(R.string.attachment_video);
            } else if(fileType.contains("audio")) {
                viewHolder.attachmentIcon.setImageResource(R.drawable.headset_24px);
                messageText = viewHolder.lastMessage.getContext().getString(R.string.attachment_audio);
            } else {
                viewHolder.attachmentIcon.setImageResource(R.drawable.attachment_file_24px);
                messageText = viewHolder.lastMessage.getContext().getString(R.string.attachment_document);
            }

            viewHolder.attachmentIcon.setVisibility(View.VISIBLE);

            if(group.lastMessage.message == null || group.lastMessage.message.length() == 0) {
                viewHolder.lastMessage.setText(messageText);
            }
        }

        if(!isMessageSentByUser) {
            viewHolder.messageStatus.setImageResource(0);
            return;
        }

        int resourceId = group.lastMessage.getStatusResourceId();

        if(resourceId != 0) {
            viewHolder.messageStatusPending.setVisibility(resourceId == -1 ? View.VISIBLE : View.GONE);

            if(resourceId != -1) {
                viewHolder.messageStatus.setImageResource(group.lastMessage.getStatusResourceId());
            } else {
                ViewUtils.setProgressBarColor(viewHolder.messageStatusPending, R.color.colorHint);
            }
        }
    }

    @Override
    public int getItemCount() {
        return mGroups.size();
    }

    class ContactViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.contact_avatar)
        CircleImageView avatar;

        @BindView(R.id.contact_name)
        TextView name;

        @BindView(R.id.contact_message_last)
        EmojiconTextView lastMessage;

        @BindView(R.id.contact_message_timestamp)
        TextView messageTimestamp;

        @BindView(R.id.contact_message_status)
        ImageView messageStatus;

        @BindView(R.id.contact_message_pending)
        ProgressBar messageStatusPending;

        @BindView(R.id.attachmentImageView)
        ImageView attachmentIcon;

        ContactViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        @OnClick(R.id.contact_container)
        void onClickContact() {
            int type = getItemViewType();

            if(mGroups.size() < getAdapterPosition()) {
                Log.e("Error", "index out of bounds! group count: " + mGroups.size() + "; adapter position: " + getAdapterPosition());
                return;
            }

            if(type == GROUP_TYPE) {
                mItemClickListener.onOpenGroupMessage(mGroups.get(getAdapterPosition()));
                return;
            }

            mItemClickListener.onOpenPrivateMessage(mGroups.get(getAdapterPosition()));
        }
    }
}
