package me.arimelody.aridroid;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.LruCache;
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.recyclerview.widget.RecyclerView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class ArtistListAdapter extends RecyclerView.Adapter<ArtistListAdapter.ArtistViewHolder> {
    Context context;
    Handler handler;
    ArrayList<ArtistModel> artists;
    LruCache<URL, Bitmap> avatarCache;

    public ArtistListAdapter(@NonNull Context context) {
        this.context = context;
        handler = new Handler(Looper.getMainLooper());
        artists = new ArrayList<>();

        avatarCache = new LruCache<>(32);
    }

    public void addArtist(ArtistModel artist) {
        artists.add(artist);
        handler.post(() -> notifyItemInserted(artists.size()));
    }

    public void removeArtist(int position) {
        artists.remove(position);
        handler.post(() -> notifyItemRemoved(position));
    }

    public void clearArtists() {
        int size = artists.size();
        artists.clear();
        handler.post(() -> 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(new View.OnClickListener() {
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(artist.getWebsite()));
                context.startActivity(browserIntent);
            }
        });
        holder.name.setText(artist.getName());
        if (!artist.getAvatarURL().isEmpty())
            holder.fetchAvatar(artist.getAvatarURL(), avatarCache);
    }

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

    public static class ArtistViewHolder extends RecyclerView.ViewHolder {
        ImageView avatar;
        TextView name;
        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);
        }

        void fetchAvatar(String avatarURL, LruCache<URL, Bitmap> avatarCache) {
            Thread thread = new Thread(() -> {
                try {
                    URL url = new URL(MainActivity.BASE_URL + avatarURL);

                    // check cache
                    Bitmap cachedImage = avatarCache.get(url);
                    if (cachedImage != null) {
                        avatar.post(() -> avatar.setImageBitmap(cachedImage));
                        return;
                    }

                    System.out.printf("Fetching %s...\n", url);
                    HttpURLConnection http = (HttpURLConnection) url.openConnection();
                    http.setRequestMethod("GET");
                    http.setRequestProperty("User-Agent", "aridroid/" + MainActivity.VERSION);
                    http.setRequestProperty("Accept", "image/*");

                    InputStream stream = http.getInputStream();
                    Bitmap img = BitmapFactory.decodeStream(stream);
                    // store image in memory cache
                    avatarCache.put(url, img);
                    avatar.post(() -> avatar.setImageBitmap(img));
                } catch (Exception e) {
                    System.err.printf("FATAL: Failed to fetch release artwork: %s\n", e);
                }
            });
            thread.start();
        }
    }
}
