package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func findmodlist(modlist string) bool {
	if !isItReal(modlist) {
		return false
	} else {
		return true
	}
}

func download(filedest string, url string) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	out, err := os.Create(filedest)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	return err
}

func downloadMods(modlist string) {
	var c = readCfg("config.yml")
	fmt.Printf("Updating mods from %s\n", modlist)
	file, err := os.Open(modlist)
	if err != nil {
		log.Fatalf("Error reading modlist: %v", err)
	}
	defer file.Close()
	var modList ModList
	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&modList); err != nil {
		log.Fatalf("Error reading JSON: %v", err)
	}

	for _, mod := range modList.Mods {
		switch mod.Name {
		case "base":
			fmt.Println("Skipping base...")
		case "elevated-rails":
			fmt.Println("Skipping elevated-rails...")
		case "quality":
			fmt.Println("Skipping quality...")
		case "space-age":
			fmt.Println("Skipping space-age...")
		default:
			modportalurl := fmt.Sprintf("https://mods.factorio.com/api/mods/%s", mod.Name)
			resp, err := http.Get(modportalurl)
			if err != nil {
				log.Fatalf("Error reading JSON: %v", err)
			}
			defer resp.Body.Close()

			var moddata ModPortal
			if err := json.NewDecoder(resp.Body).Decode(&moddata); err != nil {
				log.Fatalf("Error reading JSON: %v", err)
			}

			fmt.Printf("Mod: %s, Ver: %s, Enabled: %t\n", mod.Name, mod.Version, mod.Enabled)

			accessToken := fmt.Sprintf("?username=%s&token=%s", c.Factoryman.UserName, c.Factoryman.ApiToken)
			modDownloadUrl := fmt.Sprintf("https://mods.factorio.com%s%s", moddata.Releases[len(moddata.Releases)-1].DownloadUrl, accessToken)
			fmt.Println(modDownloadUrl)
			downloadErr := download(string(c.Server.ServDir+"/mods/"+moddata.Releases[len(moddata.Releases)-1].Filename), modDownloadUrl)
			if downloadErr != nil {
				log.Fatalf("Error downloading: %v", downloadErr)
			}
			fmt.Printf("Downloaded: %s\n", moddata.Releases[len(moddata.Releases)-1].Filename)
		}

	}

}
