package main

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

func downloadMods(c UsrConfig) {
	if hasInternet() == true {

		//var c = readCfg("config.yml")
		modlist := string(c.Server.ServDir) + "/mods/mod-list.json"

		fmt.Printf("Updating mods from %s\n", modlist)

		//read from modlist
		file, err := os.Open(modlist)
		if err != nil {
			log.Fatalf("Error reading modlist: %v", err)
		}
		defer file.Close()

		// create temp directory
		tempDir, err := os.MkdirTemp("", "factoryman-*")
		if err != nil {
			log.Fatalln("Failed to create temporary directory")
		}
		defer os.RemoveAll(tempDir)

		//decode json response from api
		var modList ModList
		decoder := json.NewDecoder(file)
		if err := decoder.Decode(&modList); err != nil {
			log.Fatalf("Error reading JSON: %v", err)
		}
		// Iterate over modlist.json
		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:
				// query mod on modportal api
				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()

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

				// query download url for mod
				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)
				fileName := string(tempDir + "/" + moddata.Releases[len(moddata.Releases)-1].Filename)
				//download mod archive
				downloadErr := download(fileName, modDownloadUrl)
				if downloadErr != nil {
					log.Fatalf("Error downloading: %v", downloadErr)
				}
				fmt.Printf("Downloaded: %s\n", fileName)
				fmt.Printf("extracting files to %s\n", c.Server.ServDir+"/mods/")
				// extract archive to mods folder
				//exec.Command("unzip", fileName, "-d", c.Server.ServDir+"/mods/")
				_, extracterr := unzip(fileName, c.Server.ServDir+"/mods/")
				if extracterr != nil {
					log.Fatalf("Error extracting archive: %v", extracterr)
				}
			}

		}
	} else {
		fmt.Println("Unable to access internet, please check connection.")
	}
}
