package main

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

	wruntime "github.com/wailsapp/wails/v2/pkg/runtime"
)

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
	Hashed       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)
	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, a *App) {
	a.Status(fmt.Sprintf("Checking %s\n", lib.Name))
	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
		}
	}
	a.Status(fmt.Sprintf("Downloading %s\n", lib.Name))
	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()
	if resp.StatusCode != 200 {
		fmt.Printf("unable to find library: %s\n", lib.Url+path)
		return
	}
	buff := new(bytes.Buffer)
	downloaded := 0
	for {
		count, err := io.CopyN(buff, resp.Body, BlockSize)
		if err == io.EOF {
			downloaded += int(count)
			break
		}
		if err != nil {
			fmt.Printf("Error Downloading libs: %e\n", err)
			return
		}
		downloaded += int(count)
		wruntime.EventsEmit(a.Ctx, "download", downloaded, resp.ContentLength)
	}
	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, buff)
	wruntime.EventsEmit(a.Ctx, "download_complete")
}

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