package engine

import (
	"encoding/json"
	"io/ioutil"
	"os"
)

// This is the entire JSON File Struct so we can modify it as needed
type unrealProjectJSON struct {
	FileVersion       int    `json:"FileVersion"`
	EngineAssociation string `json:"EngineAssociation"`
	Category          string `json:"Category"`
	Description       string `json:"Description"`
	Modules           []struct {
		Name                   string   `json:"Name"`
		Type                   string   `json:"Type"`
		LoadingPhase           string   `json:"LoadingPhase"`
		AdditionalDependencies []string `json:"AdditionalDependencies,omitempty"`
	} `json:"Modules"`
	Plugins []struct {
		Name                     string   `json:"Name"`
		Enabled                  bool     `json:"Enabled"`
		MarketplaceURL           string   `json:"MarketplaceURL,omitempty"`
		SupportedTargetPlatforms []string `json:"SupportedTargetPlatforms,omitempty"`
	} `json:"Plugins"`
}

func editProjectFile(projectFile os.FileInfo, enableRider bool) error {
	byteValue, err := ioutil.ReadFile(projectFile.Name())
	if err != nil {
		return err
	}

	var projectStruct unrealProjectJSON
	json.Unmarshal([]byte(byteValue), &projectStruct)

	for i, plugin := range projectStruct.Plugins {
		if plugin.Name == "OculusVR" {
			projectStruct.Plugins[i].Enabled = false

		}
		if plugin.Name == "SteamVR" {
			projectStruct.Plugins[i].Enabled = false

		}
		if plugin.Name == "RiderLink" {
			if enableRider {
				projectStruct.Plugins[i].Enabled = true
			} else {
				projectStruct.Plugins[i].Enabled = false
			}
		}
	}
	file, err := json.MarshalIndent(projectStruct, "", "\t")
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(projectFile.Name(), file, 0644)
	if err != nil {
		return err
	}
	return nil
}
