package generator

import (
	"fmt"
	"math"
)

const defaultFactor float64 = 0.1

type MapSetting struct {
	Players       uint32
	HWSize        float64
	HWResources   float64
	HWMinDistance uint32
	DWCount       uint32
	DWSize        float64
	DWResources   float64
	DWMinDistance uint32
	DWMaxDistance uint32

	GiantPlanets      PlanetSetting
	BigPlanets        PlanetSetting
	OthersMinDistance float64
	NormalPlanets     PlanetSetting
	RichPlanets       PlanetSetting
	Asterioids        PlanetSetting
}

func (ms MapSetting) String() string {
	return fmt.Sprintf("MapSetting[players=%d HWMinDistance=%d Size=%d]", ms.Players, ms.HWMinDistance, ms.ExpectedSize())
}

func (ms MapSetting) ExpectedSize() uint32 {
	return uint32(math.Sqrt(float64(ms.Players)) * float64(ms.HWMinDistance) * 1.5)
}

func (ms MapSetting) TotalPlanets() uint32 {
	return ms.Players * 10
}

func (ms MapSetting) NobodysPlanets() uint32 {
	return ms.TotalPlanets() - ms.Players*(ms.DWCount+1)
}

type PlanetSetting struct {
	MinDistanceHW uint32
	MinSize       float64
	MaxSize       float64
	MinResource   float64 // Rules: [0.1, 20]
	MaxResource   float64
	Ratio         float64 // The proportion of the total number of free planets in the galaxy
}

// Number of planets need to be placed within freePlanets amount
func (ps PlanetSetting) Number(freePlanets uint32) int {
	return int(math.Ceil(float64(freePlanets) * ps.Ratio))
}

func DefaultMapSetting() MapSetting {
	return MapSetting{
		Players:       25,
		HWSize:        1000,
		HWResources:   10,
		HWMinDistance: 30,
		DWCount:       2,
		DWSize:        500,
		DWResources:   10,
		DWMinDistance: 5,
		DWMaxDistance: 15,
		GiantPlanets: PlanetSetting{
			MinDistanceHW: 20,
			MinSize:       1500,
			MaxSize:       2500,
			MinResource:   0.1,
			MaxResource:   3,
			Ratio:         0.06,
		},
		BigPlanets: PlanetSetting{
			MinDistanceHW: 10,
			MinSize:       1000,
			MaxSize:       2000,
			MinResource:   1,
			MaxResource:   10,
			Ratio:         0.18,
		},
		OthersMinDistance: defaultFactor, // min. is 1 pixel on the plotter
		NormalPlanets: PlanetSetting{
			MinDistanceHW: 0,
			MinSize:       0,
			MaxSize:       1000,
			MinResource:   0.1,
			MaxResource:   10,
			Ratio:         0.5,
		},
		RichPlanets: PlanetSetting{
			MinDistanceHW: 0,
			MinSize:       0,
			MaxSize:       500,
			MinResource:   5,
			MaxResource:   25,
			Ratio:         0.18,
		},
		Asterioids: PlanetSetting{
			MinDistanceHW: 0,
			MinSize:       0,
			MaxSize:       0,
			MinResource:   0,
			MaxResource:   0,
			Ratio:         0.08,
		},
	}
}
