package me.arimelody.aridroid;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.json.JSONObject;

import java.net.URI;
import java.net.URL;

public class ReleaseViewActivity extends AppCompatActivity {
    ImageView releaseArtwork;
    TextView releaseTitle;
    TextView releaseArtist;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null) throw new RuntimeException("ReleaseViewActivity started without a release ID");

        String releaseID = bundle.getString("release");

        setContentView(R.layout.activity_view_release);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.release_view), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        releaseArtwork = findViewById(R.id.release_artwork);
        releaseTitle = findViewById(R.id.release_title);
        releaseArtist = findViewById(R.id.release_artist);

        Thread fetchThread = new Thread(() -> {
            JSONObject data;
            ReleaseModel release = Cache.releases.get(releaseID);
            if (release == null) {
                // FETCH RELEASE DATA
                try {
                    URL url = URI.create(getResources().getString(R.string.base_url) + "/api/v1/music/" + releaseID).toURL();
                    data = SimpleDownloader.getJSONObject(url);
                } catch (Exception e) {
                    System.err.printf("Failed to fetch data for %s: %s\n", releaseID, e);
                    Looper.prepare();
                    Toast.makeText(this, "Failed to fetch release data", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }

                // PARSE RELEASE DATA
                try {
                    release = new ReleaseModel(data);
                } catch (Exception e) {
                    System.err.printf("Failed to parse data for %s: %s\n", releaseID, e);
                    Looper.prepare();
                    Toast.makeText(this, "Failed to parse release data", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }

                Cache.releases.put(releaseID, release);
            }

            StringBuilder artists = new StringBuilder();
            for (int i = 0; i < release.getCredits().size(); i++) {
                if (!release.getCredits().get(i).isPrimary()) continue;
                ArtistModel artist = release.getCredits().get(i).getArtist();
                if (i == 0) {
                    artists.append(artist.getName());
                    continue;
                }
                if (i == release.getCredits().size() - 1) {
                    artists.append(" & ").append(artist.getName());
                    break;
                }
                artists.append(", ").append(artist.getName());
            }

            String artworkURL = release.getArtworkURL();
            Thread artworkThread = new Thread(() -> {
                URL url;
                try {
                    url = new URI(getResources().getString(R.string.base_url) + artworkURL).toURL();
                } catch (Exception e) {
                    Log.w(Constants.TAG, "Failed to fetch release artwork " + artworkURL);
                    return;
                }

                // check cache
                Drawable cachedImg = Cache.drawables.get(url.toString());
                if (cachedImg != null) {
                    findViewById(R.id.release_view).post(() -> releaseArtwork.setImageDrawable(cachedImg));
                    return;
                }
                // cache miss. download it!
                Drawable img;
                Bitmap bmp = SimpleDownloader.getImage(url);
                if (bmp != null) {
                    img = new BitmapDrawable(getResources(), bmp);
                } else {
                    img = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_launcher, null);
                }
                // store image in memory cache
                Cache.drawables.put(url.toString(), img);
                findViewById(R.id.release_view).post(() -> releaseArtwork.setImageDrawable(img));
            });
            artworkThread.start();

            String title = release.getTitle();
            findViewById(R.id.release_view).post(() -> {
                releaseTitle.setText(title);
                releaseArtist.setText(artists);
            });
        });
        fetchThread.start();
    }
}
