package me.arimelody.aridroid;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.RecyclerView;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class ArtistListAdapter extends RecyclerView.Adapter<ArtistListAdapter.ArtistViewHolder> {
    private final Context context;
    private final ArrayList<ArtistModel> artists;

    public ArtistListAdapter(@NonNull Context context) {
        this.context = context;
        artists = new ArrayList<>();
    }

    public void addArtist(ArtistModel artist) {
        artists.add(artist);
        notifyItemInserted(artists.size());
    }

    public void removeArtist(int position) {
        artists.remove(position);
        notifyItemRemoved(position);
    }

    public void clearArtists() {
        int size = artists.size();
        artists.clear();
        notifyItemRangeRemoved(0, size);
    }

    @NonNull
    @Override
    public ArtistViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.artist_list_item, parent, false);
        return new ArtistViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ArtistViewHolder holder, int position) {
        ArtistModel artist = artists.get(position);

        holder.website.setOnClickListener(v -> {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(artist.getWebsite()));
            context.startActivity(browserIntent);
        });

        holder.name.setText(artist.getName());

        if (!artist.getAvatarURL().isEmpty()) {
            Thread thread = new Thread(() -> {
                URL url;
                try {
                    url = new URL(context.getResources().getString(R.string.base_url) + artist.getAvatarURL());
                } catch (MalformedURLException e) {
                    throw new RuntimeException(e);
                }

                // check cache
                Drawable cachedImage = Cache.drawables.get(url.toString());
                if (cachedImage != null) {
                    holder.avatar.post(() -> holder.avatar.setImageDrawable(cachedImage));
                    return;
                }
                // cache miss. download it!
                Drawable img;
                Bitmap bmp = SimpleDownloader.getImage(url);
                if (bmp != null) {
                    img = new BitmapDrawable(context.getResources(), bmp);
                } else {
                    img = ResourcesCompat.getDrawable(context.getResources(), R.mipmap.ic_launcher, null);
                }
                // store image in memory cache
                Cache.drawables.put(url.toString(), img);
                holder.avatar.post(() -> holder.avatar.setImageDrawable(img));
            });
            thread.start();
        }
        holder.avatar.setContentDescription(context.getString(R.string.artist_avatar_description, artist.getName()));
    }

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

    public static class ArtistViewHolder extends RecyclerView.ViewHolder {
        public final ImageView avatar;
        public final TextView name;
        public final Button website;

        public ArtistViewHolder(@NonNull View itemView) {
            super(itemView);

            avatar = itemView.findViewById(R.id.artistAvatar);
            name = itemView.findViewById(R.id.artistName);
            website = itemView.findViewById(R.id.artistWebsite);
        }
    }
}
