package gitService

import (
	"encoding/json"
	"firefly-launcher/pkg/constant"
	"firefly-launcher/pkg/models"
	"io"
	"net/http"
	"github.com/minio/selfupdate"

)

type GitService struct{}


func (g *GitService) GetLatestLauncherVersion() (bool, string, string) {
	resp, err := http.Get(constant.LauncherGitUrl)
	if err != nil {
		return false, "", err.Error()
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)

	var releases []models.ReleaseType
	err = json.Unmarshal(body, &releases)
	if err != nil {
		return false, "", err.Error()
	}

	if len(releases) == 0 {
		return false, "", "no releases found"
	}

	return true, releases[0].TagName, ""
}



func (g *GitService) UpdateLauncherProgress(version string) (bool, string) {
	resp, err := http.Get(constant.LauncherGitUrl)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)

	var releases []*models.ReleaseType
	err = json.Unmarshal(body, &releases)
	if err != nil {
		return false, err.Error()
	}

	if len(releases) == 0 {
		return false, "no releases found"
	}

	var releaseData *models.ReleaseType
	for _, release := range releases {
		if release.TagName == version {
			releaseData = release
			break
		}
	}

	if releaseData == nil || releaseData.TagName == "" {
		return false, "no release found"
	}

	var assetWin models.AssetType
	for _, asset := range releaseData.Assets {
		if asset.Name == constant.LauncherFile {
			assetWin = asset
			break
		}
	}

	if assetWin.Name == "" {
		return false, "no assets found"
	}

	resp, err = http.Get(assetWin.BrowserDownloadURL)
	if err != nil {
		return false, err.Error()
	}
	defer resp.Body.Close()
	err = selfupdate.Apply(resp.Body, selfupdate.Options{})
	if err != nil {
		return false, err.Error()
	}
	return true, ""
}
