package scheme

import (
	"Server-Core/Server/Base"
	"errors"
	"fmt"
	"net"
	"reflect"
	"strconv"
)

type ItemItem struct {
	Id      int32
	Quality int32
	Price   int32
	Type    string
	Value   int32
}

type Item struct {
	dataList map[int32]*ItemItem
}

var ip string = ""

func getIp() string {

	addrList, err := net.InterfaceAddrs()
	if err != nil {
		panic(err)
	}
	for _, address := range addrList {
		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				fmt.Println(ipNet.IP.String())
				ip = ipNet.IP.String()
				break
			}
		}
	}
	return ip
}

func (scp *Item) Load() {
	scp.dataList = make(map[int32]*ItemItem)
	getIp()
	fmt.Printf("exPath", ip)
	//records := base.LoadCsvCfg("../Scp/Item.csv").Records
	//records := base.LoadCsvCfg("../Scp/Item.csv").Records
	//records := base.LoadCsvCfg("./Scp/Item.csv").Records
	var path string = ""
	if ip == "192.168.1.122" {
		path = "E://ChatGameService2/Bin/Scp/Item.csv"
	} else {
		//	records := base.LoadCsvCfg("E://ChatGameService2/Bin/Scp/Level.csv").Records
		path = "../Scp/Item.csv"
	}
	records := base.LoadCsvCfg(path).Records
	//	records := base.LoadCsvCfg("E://ChatGameService2/Bin/Scp/Item.csv").Records
	//file, err := os.Open(fmt.Sprintf("E://ChatGameService2/Scp/Item.csv", tag))
	for i := 4; i < len(records); i++ {
		item := new(ItemItem)
		cr := reflect.ValueOf(item).Elem()
		for k, v := range records[i].Record {
			k = base.StrFirstToUpper(k)
			a := cr.FieldByName(k)
			switch a.Type().String() {
			case "string":
				a.Set(reflect.ValueOf(v))
			case "int32":
				i, _ := strconv.Atoi(v)
				a.Set(reflect.ValueOf(int32(i)))
			case "float64":
				f, _ := strconv.ParseFloat(v, 64)
				a.Set(reflect.ValueOf(f))
			}
		}
		scp.dataList[item.Id] = item
	}
}

func (scp *Item) Get(key int32) (interface{}, error) {
	data, ok := scp.dataList[key]
	if ok {
		return data, nil
	} else {
		return nil, errors.New("not find")
	}
}
