package main

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
)

type Quilt struct {

}


type QuiltDefinition struct {
	Separator string
	Build int
	Maven string
	Version string
	Stable bool
}

type QuiltLibrary struct {
	Name string
	Url string
	Sha1 string
}

type QuiltLibraries struct {
	Client []QuiltLibrary
	Common []QuiltLibrary
	Server []QuiltLibrary
}

type QuiltMeta struct {
	Version int
	Libraries QuiltLibraries
	MainClass map[string]string
}

type QuiltVersion struct {
	Loader QuiltDefinition
	Intermediary QuiltDefinition
	LauncherMeta QuiltMeta
}

func (Quilt)GetQuiltVersions(mcVersion string) ([]QuiltVersion, error) {
	resp, err := http.Get("https://meta.quiltmc.org/v3/versions/loader/"+mcVersion)
	if err != nil {
		return []QuiltVersion{}, fmt.Errorf("Unable to pull quilt version manifest: %s\n", err)
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	versions := []QuiltVersion{}
	json.Unmarshal(data, &versions)
	fmt.Printf("Quilt Versions: %s\n", data)
	return versions, nil
}

func GetQuiltMetadata(mcVersion string, quiltVersion string) (QuiltVersion, error) {
	versions, err := Quilt{}.GetQuiltVersions(mcVersion)
	if err != nil {
		return QuiltVersion{}, fmt.Errorf("unable to download versions manifest: %e\n", err)
	}
	for _, version := range versions {
		if version.Loader.Version == quiltVersion {
			return version, nil
		}
	}
	return QuiltVersion{}, fmt.Errorf("Unable to find requested version.\n")
}

func InstallQuiltLib(lib QuiltLibrary, libDir string) {
	path := filepath.Join(ProcessMavenPath(lib.Name), ProcessMavenFilename(lib.Name))
	if _, err := os.Stat(filepath.Join(libDir, path)); err == nil {
		f, _ := os.OpenFile(filepath.Join(libDir, path), os.O_RDONLY, 0755)
		defer f.Close()
		data, _ := io.ReadAll(f)
		sha := sha1.Sum(data)
		if hex.EncodeToString(sha[:20]) == lib.Sha1 {
			return
		}
	}
	resp, err := http.Get(lib.Url+path)
	if err != nil {
		fmt.Printf("unable to find library: %s\n", lib.Url+path)
		return
	}
	defer resp.Body.Close()
	os.MkdirAll(filepath.Join(libDir, ProcessMavenPath(lib.Name)), 0755)
	f, _ := os.OpenFile(filepath.Join(libDir, path), os.O_CREATE|os.O_RDWR, 0755)
	defer f.Close()
	io.Copy(f, resp.Body)
}

func InstallQuiltLibs(mcVersion string, quiltVersion string, libDir string) {
	metadata, _ := GetQuiltMetadata(mcVersion, quiltVersion)
	for _, lib := range metadata.LauncherMeta.Libraries.Client {
		InstallQuiltLib(lib, libDir)
	}	
	for _, lib := range metadata.LauncherMeta.Libraries.Common {
		InstallQuiltLib(lib, libDir)
	}	
	InstallQuiltLib(QuiltLibrary{Name: metadata.Loader.Maven, Sha1: "", Url: "https://maven.fabricmc.net/"}, libDir)
	InstallQuiltLib(QuiltLibrary{Name: metadata.Intermediary.Maven, Sha1: "", Url: "https://maven.fabricmc.net/"}, libDir)
}

