package gitService

import (
	"firefly-launcher/pkg/constant"
	"firefly-launcher/pkg/models"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"encoding/json"
	"github.com/wailsapp/wails/v3/pkg/application"
)

func (g *GitService) GetLatestProxyVersion() (bool, string, string) {
	resp, err := http.Get(constant.ProxyGitUrl)
	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) DownloadProxyProgress(version string) (bool, string) {
	resp, err := http.Get(constant.ProxyGitUrl)
	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.ProxyZipFile {
			assetWin = asset
			break
		}
	}

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

	if err := os.Mkdir(constant.ProxyStorageUrl, 0755); err != nil {
		if !os.IsExist(err) {
			return false, err.Error()
		}
	}
	saveFile := filepath.Join(constant.ProxyStorageUrl, assetWin.Name)

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

	DownloadFile(saveFile, assetWin.BrowserDownloadURL, func(percent float64, speed float64) {
		application.Get().Event.Emit("download:proxy", map[string]interface{}{
			"percent": fmt.Sprintf("%.2f", percent),
			"speed":   fmt.Sprintf("%.2f", speed),
		})

	})
	return true, ""
}

func (g *GitService) UnzipProxy() {
	unzipParallel(filepath.Join(constant.ProxyStorageUrl, constant.ProxyZipFile), constant.ProxyStorageUrl)
	os.Remove(filepath.Join(constant.ProxyStorageUrl, constant.ProxyZipFile))
}