package skill

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

var Skill skill

type skill struct {
	skills       []Conf
	skillConfMap map[int]Conf
	outline      outline
}

func (this *skill) Load() {
	this.skills = make([]Conf, 0)
	this.skillConfMap = make(map[int]Conf)

	jsonDir := config.GetPath("logic.json_data", "data/conf/json/")
	fileName := path.Join(jsonDir, "skill", "skill_outline.json")
	jdata, err := os.ReadFile(fileName)
	if err != nil {
		slog.Error("skill load file error", "error", err, "file", fileName)
		os.Exit(0)
	}

	json.Unmarshal(jdata, &this.outline)

	rd, err := os.ReadDir(path.Join(jsonDir, "skill"))
	if err != nil {
		slog.Error("skill readdir error", "error", err)
		os.Exit(0)
	}

	for _, r := range rd {
		if r.IsDir() {
			this.readSkill(path.Join(jsonDir, "skill", r.Name()))
		}
	}

	slog.Debug("skill configs loaded", "count", len(this.skills))
}

func (this *skill) readSkill(dir string) {
	rd, err := os.ReadDir(dir)
	if err == nil {
		for _, r := range rd {
			if r.IsDir() == false {
				jdata, err := os.ReadFile(path.Join(dir, r.Name()))
				if err == nil {
					conf := Conf{}
					if err := json.Unmarshal(jdata, &conf); err == nil {
						this.skills = append(this.skills, conf)
						this.skillConfMap[conf.CfgId] = conf
					} else {
						slog.Warn("Unmarshal skill error", "error", err,
							"file", path.Join(dir, r.Name()))
					}
				}
			}
		}
	}

}

func (this *skill) GetCfg(cfgId int) (Conf, bool) {
	cfg, ok := this.skillConfMap[cfgId]
	return cfg, ok
}
