package general

import (
	"encoding/json"
	"errors"
	"log/slog"
	"os"
	"path"
	"slgserver/config"
)

var GenBasic Basic

type gLevel struct {
	Level    int8 `json:"level"`
	Exp      int  `json:"exp"`
	Soldiers int  `json:"soldiers"`
}

type Basic struct {
	Title  string   `json:"title"`
	Levels []gLevel `json:"levels"`
}

func (this *Basic) Load() {
	jsonDir := config.GetPath("logic.json_data", "data/conf/json/")
	fileName := path.Join(jsonDir, "general", "general_basic.json")
	jdata, err := os.ReadFile(fileName)
	if err != nil {
		slog.Error("general load file error", "error", err, "file", fileName)
		os.Exit(0)
	}

	json.Unmarshal(jdata, this)

	slog.Debug("general basic config loaded", "levels", len(this.Levels))

	General.Load()
	GenArms.Load()
}

func (this *Basic) GetLevel(l int8) (*gLevel, error) {
	if l <= 0 {
		return nil, errors.New("level error")
	}
	if int(l) <= len(this.Levels) {
		return &this.Levels[l-1], nil
	} else {
		return nil, errors.New("level error")
	}
}

func (this *Basic) ExpToLevel(exp int) (int8, int) {
	var level int8 = 0
	limitExp := this.Levels[len(this.Levels)-1].Exp
	for _, v := range this.Levels {
		if exp >= v.Exp && v.Level > level {
			level = v.Level
		}
	}

	if limitExp < exp {
		return level, limitExp
	} else {
		return level, exp
	}
}
