package me.arimelody.aridroid;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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 java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    public static String VERSION;

    RecyclerView releaseListView;
    RecyclerView artistListView;
    ReleaseListAdapter releaseListAdapter;
    ArtistListAdapter artistListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        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);
        }

        releaseListView = findViewById(R.id.musicList);
        releaseListAdapter = new ReleaseListAdapter(this);
        releaseListView.setAdapter(releaseListAdapter);
        releaseListView.setLayoutManager(new LinearLayoutManager(this));

        artistListView = findViewById(R.id.artistList);
        artistListAdapter = new ArtistListAdapter(this);
        artistListView.setAdapter(artistListAdapter);
        artistListView.setLayoutManager(new LinearLayoutManager(this));

        Thread releaseFetchThread = new Thread(() -> {
            try {
                URL url;
                try {
                    url = URI.create(getResources().getString(R.string.base_url) + "/api/v1/music").toURL();
                } catch (MalformedURLException e) {
                    throw new RuntimeException(e);
                }

                JSONArray json;
                try {
                    json = SimpleDownloader.getJSONArray(url);
                } catch (IOException e) {
                    Toast.makeText(this, "Failed to fetch release data", Toast.LENGTH_SHORT).show();
                    Log.e(Constants.TAG, "Failed to fetch release data: " + e);
                    return;
                } catch (JSONException e) {
                    Toast.makeText(this, "Failed to parse release data", Toast.LENGTH_SHORT).show();
                    Log.e(Constants.TAG, "Failed to parse release data: " + e);
                    return;
                }

                releaseListAdapter.clearReleases();

                for (int i = 0; i < json.length(); i++) {
                    ReleaseModel release;
                    try {
                        release = new ReleaseModel(json.getJSONObject(i));
                    } catch (JSONException e) {
                        Log.w(Constants.TAG, "Failed to parse release data at index " + i);
                        continue;
                    }

                    releaseListView.post(() -> releaseListAdapter.addRelease(release));
                    if (i == 0) releaseListView.post(() -> findViewById(R.id.musicListThrobber).setVisibility(RecyclerView.GONE));
                }
            } finally {
                releaseListView.post(() -> findViewById(R.id.musicListThrobber).setVisibility(RecyclerView.GONE));
            }
        });

        Thread artistFetchThread = new Thread(() -> {
            try {
                URL url;
                try {
                    url = URI.create(getResources().getString(R.string.base_url) + "/api/v1/artist").toURL();
                } catch (MalformedURLException e) {
                    throw new RuntimeException(e);
                }

                JSONArray json;
                try {
                    json = SimpleDownloader.getJSONArray(url);
                } catch (IOException e) {
                    Toast.makeText(this, "Failed to fetch artist data", Toast.LENGTH_SHORT).show();
                    Log.e(Constants.TAG, "Failed to fetch artist data: " + e);
                    return;
                } catch (JSONException e) {
                    Toast.makeText(this, "Failed to parse artist data", Toast.LENGTH_SHORT).show();
                    Log.e(Constants.TAG, "Failed to parse artist data: " + e);
                    return;
                }
                artistListAdapter.clearArtists();

                for (int i = 0; i < json.length(); i++) {
                    ArtistModel artist;
                    try {
                        artist = new ArtistModel(json.getJSONObject(i));
                    } catch (JSONException e) {
                        Log.w(Constants.TAG, "Failed to parse artist data at index " + i);
                        continue;
                    }

                    boolean first = i == 0;
                    artistListView.post(() -> {
                        artistListAdapter.addArtist(artist);
                        if (first) findViewById(R.id.artistListThrobber).setVisibility(RecyclerView.GONE);
                    });
                }
            } finally {
                artistListView.post(() -> findViewById(R.id.artistListThrobber).setVisibility(RecyclerView.GONE));
            }
        });

        releaseFetchThread.start();
        artistFetchThread.start();
    }
}
