package util

import (
	"ARKItems/entity/ark"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
)

//读取ark shop配置

func LoadArkShopConfig(url string) (
	ark.Config, map[string]ark.ShopItem, map[string]ark.ShopDino,
	map[string]ark.ShopBeacon, map[string]ark.ShopExperience,
	map[string]ark.ShopUnlockengram, map[string]ark.ShopCommand) {
	file, err := os.OpenFile(url, os.O_RDWR, 0666)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	all, err := io.ReadAll(file)
	if err != nil {
		panic(err)
	}
	index := strings.Index(string(all), "{")
	all = []byte(string(all)[index:])

	return LoadArkShopConfigByString(all)
}

func LoadArkShopConfigByString(jsonContent []byte) (
	ark.Config, map[string]ark.ShopItem, map[string]ark.ShopDino,
	map[string]ark.ShopBeacon, map[string]ark.ShopExperience,
	map[string]ark.ShopUnlockengram, map[string]ark.ShopCommand) {
	var config ark.Config

	var ARKShopItems = make(map[string]ark.ShopItem)
	var ARKShopDines = make(map[string]ark.ShopDino)
	var ARKShopBeacons = make(map[string]ark.ShopBeacon)
	var ARKShopExperiences = make(map[string]ark.ShopExperience)
	var ARKShopUnlockengram = make(map[string]ark.ShopUnlockengram)
	var ARKShopCommands = make(map[string]ark.ShopCommand)

	err := json.Unmarshal(jsonContent, &config)
	if err != nil {
		panic(err)
	}
	//接卸shopItems内容
	var m map[string]interface{}
	err = json.Unmarshal(jsonContent, &m)
	if err != nil {
		panic(err)
	}
	ShopItems, ok := m["ShopItems"].(map[string]interface{})
	if ok {
		for key := range ShopItems {
			item := ShopItems[key].(map[string]interface{})
			t := item["Type"]

			switch t {
			case "item":
				var obj ark.ShopItem
				DataToObject(item, &obj)
				ARKShopItems[key] = obj
				continue
			case "dino":
				var obj ark.ShopDino
				DataToObject(item, &obj)
				ARKShopDines[key] = obj
				continue
			case "beacon":
				var obj ark.ShopBeacon
				DataToObject(item, &obj)
				ARKShopBeacons[key] = obj
				continue
			case "experience":
				var obj ark.ShopExperience
				DataToObject(item, &obj)
				ARKShopExperiences[key] = obj
				continue
			case "unlockengram":
				var obj ark.ShopUnlockengram
				DataToObject(item, &obj)
				ARKShopUnlockengram[key] = obj
				continue
			case "command":
				var obj ark.ShopCommand
				DataToObject(item, &obj)
				ARKShopCommands[key] = obj
				continue
			default:
				fmt.Println("=================>", t)
			}
		}
	} else {
		panic("ShopItems is not a map")
	}
	return config, ARKShopItems, ARKShopDines, ARKShopBeacons, ARKShopExperiences, ARKShopUnlockengram, ARKShopCommands
}
