package com.example.punyaria;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;

import java.util.List;

public class ChatAdapter extends ArrayAdapter<ChatMessage> {
    private Activity context;
    private List<ChatMessage> messages;
    private String currentUser;

    public ChatAdapter(Activity context, List<ChatMessage> messages, String currentUser) {
        super(context, R.layout.chat_message_item, messages);
        this.context = context;
        this.messages = messages;
        this.currentUser = currentUser;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ChatMessage message = messages.get(position);
        LayoutInflater inflater = context.getLayoutInflater();

        View listViewItem;

        if (message.getUsername().equals(currentUser)) {
            // Message sent by the logged-in user
            listViewItem = inflater.inflate(R.layout.chat_message_sent, null, true);
            TextView textViewMessageSent = listViewItem.findViewById(R.id.text_message_sent);
            ImageView imageViewMessageSent = listViewItem.findViewById(R.id.image_message_sent);

            if (message.isImage()) {
                textViewMessageSent.setVisibility(View.GONE);
                imageViewMessageSent.setVisibility(View.VISIBLE);
                Glide.with(context).load(message.getImageUrl()).into(imageViewMessageSent);
            } else {
                imageViewMessageSent.setVisibility(View.GONE);
                textViewMessageSent.setVisibility(View.VISIBLE);
                textViewMessageSent.setText(message.getMessage());
            }
        } else {
            // Message received from other users
            listViewItem = inflater.inflate(R.layout.chat_message_received, null, true);
            TextView textViewMessageReceived = listViewItem.findViewById(R.id.text_message_received);
            ImageView imageViewMessageReceived = listViewItem.findViewById(R.id.image_message_received);

            if (message.isImage()) {
                textViewMessageReceived.setVisibility(View.GONE);
                imageViewMessageReceived.setVisibility(View.VISIBLE);
                Glide.with(context).load(message.getImageUrl()).into(imageViewMessageReceived);
            } else {
                imageViewMessageReceived.setVisibility(View.GONE);
                textViewMessageReceived.setVisibility(View.VISIBLE);
                textViewMessageReceived.setText(message.getMessage());
            }
        }

        return listViewItem;
    }
}
