package me.arimelody.aridroid;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    public static String BASE_URL;
    public static String VERSION;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            VERSION = pInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }

        BASE_URL = getResources().getString(R.string.base_url);

        ReleaseListAdapter releaseListAdapter = new ReleaseListAdapter(this);
        fetchReleaseData(releaseListAdapter);
        ArtistListAdapter artistListAdapter = new ArtistListAdapter(this);
        fetchArtistData(artistListAdapter);

        RecyclerView releaseList = findViewById(R.id.musicList);
        releaseList.setAdapter(releaseListAdapter);
        releaseList.setLayoutManager(new LinearLayoutManager(this));

        RecyclerView artistList = findViewById(R.id.artistList);
        artistList.setAdapter(artistListAdapter);
        artistList.setLayoutManager(new LinearLayoutManager(this));
    }

    void fetchReleaseData(ReleaseListAdapter releaseListAdapter) {
        Thread thread = new Thread(() -> {
                try {
                    URL url = URI.create(BASE_URL + "/api/v1/music").toURL();
                    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", "application/json");

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = http.getInputStream().read(buffer)) != -1) {
                        stream.write(buffer, 0, length);
                    }
                    updateReleaseList(stream.toString(), releaseListAdapter);
                } catch (Exception e) {
                    System.err.printf("Failed to fetch music data: %s\n", e);
                }
        });
        thread.start();
    }

    void updateReleaseList(String res, ReleaseListAdapter releaseListAdapter) {
        try {
            JSONArray json = new JSONArray(res);
            releaseListAdapter.clearReleases();

            for (int i = 0; i < json.length(); i++) {
                JSONObject obj = json.getJSONObject(i);

                ArrayList<MusicCreditModel> credits = new ArrayList<>();

                JSONArray jsonArtists = obj.getJSONArray("artists");
                for (int ci = 0; ci < jsonArtists.length(); ci++)
                    credits.add(new MusicCreditModel("", jsonArtists.getString(ci), "", true));
                String buylink = obj.getString("buylink");

                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.GERMANY);
                Date date;
                try {
                    date = df.parse(obj.getString("releaseDate"));
                } catch (ParseException e) {
                    System.err.printf("Failed to parse date for release %s: %s\n", obj.getString("id"), e);
                    continue;
                }

                releaseListAdapter.addRelease(new ReleaseModel(
                        obj.getString("id"),
                        obj.getString("title"),
                        "",
                        obj.getString("type"),
                        date,
                        obj.getString("artwork"),
                        "Buy",
                        buylink,
                        obj.getString("copyright"),
                        null,
                        credits));
            }
        } catch (JSONException e) {
            System.err.printf("Failed to parse JSON response: %s\n", e);
        }
    }

    void fetchArtistData(ArtistListAdapter artistListAdapter) {
        Thread thread = new Thread(() -> {
            try {
                URL url = URI.create(BASE_URL + "/api/v1/artist").toURL();
                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", "application/json");

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = http.getInputStream().read(buffer)) != -1) {
                    stream.write(buffer, 0, length);
                }
                updateArtistList(stream.toString(), artistListAdapter);
            } catch (Exception e) {
                System.err.printf("Failed to fetch artist data: %s\n", e);
            }
        });
        thread.start();
    }

    void updateArtistList(String res, ArtistListAdapter artistListAdapter) {
        try {
            JSONArray json = new JSONArray(res);
            artistListAdapter.clearArtists();

            for (int i = 0; i < json.length(); i++) {
                JSONObject obj = json.getJSONObject(i);

                artistListAdapter.addArtist(new ArtistModel(
                        obj.getString("id"),
                        obj.getString("name"),
                        obj.getString("website"),
                        obj.getString("avatar")));
            }
        } catch (JSONException e) {
            System.err.printf("Failed to parse JSON response: %s\n", e);
        }
    }
}
