package base

import (
	"Server-Core/Server/Base/Log"
	service "Server-Core/Server/Base/Service"
	"Server-Core/Server/Common"
	"bufio"
	"flag"
	"fmt"
	"net"
	"os"
	"os/signal"
	"reflect"
	"strconv"
	"strings"
	"syscall"
	"time"
)

var Server *ServerBase

type ServerBase struct {
	running bool
	Config  common.ServerConf
	net     *Net
	Timer   *Timer
	Execute ServerExecute

	kill chan os.Signal
}

// var siteMap1 map[string]string = make(map[string]string)

func NewServer(execute ServerExecute) {
	Server = new(ServerBase)
	Server.kill = make(chan os.Signal, 1)
	signal.Notify(Server.kill, syscall.SIGINT, syscall.SIGTERM)
	Server.readServerConfig()
	log.AddRotateHook(".././Log", 30, true)

	log.Info("系统初始化")
	err := service.Init()
	if err != nil {
		panic(err)
	}
	log.Info("创建服务管理 Success")
	Server.Execute = execute
	log.Info("============")
	Server.start()
}

func (s *ServerBase) start() {
	s.running = true

	s.Execute.LogicStart()
	s.Execute.OnServerReady()

	for s.running {
		select {
		case <-time.After(16 * time.Millisecond):
			service.Run()
		case <-s.kill:
			s.running = false
			log.Info("系统开始关闭")
		}
	}

	s.Execute.LogicEnd()
	s.stop()
}

func (s *ServerBase) stop() {
	service.UnInit()
}

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 (s *ServerBase) readServerConfig() {
	var tag string
	cr := reflect.ValueOf(&s.Config).Elem()
	flag.StringVar(&tag, "tag", "dev", "--tag=dev")
	flag.Parse()
	ip = getIp()
	if ip == "192.168.1.122" {
		file, err := os.Open(fmt.Sprintf("E://ChatGameService2/Bin/Config/%s.conf", tag))
		if err != nil {
			panic(err)
		}
		defer file.Close()
		sc := bufio.NewScanner(file)
		for sc.Scan() {
			var str = sc.Text()
			var index = strings.Index(str, "=")
			if index == -1 {
				continue
			}
			var key = strings.Trim(str[0:index], " ")
			var value = strings.Trim(str[index+1:], " ")
			a := cr.FieldByName(key)
			switch a.Type().String() {
			case "string":
				value = strings.Trim(value, "\"")
				a.Set(reflect.ValueOf(value))
			case "bool":
				b, _ := strconv.ParseBool(value)
				a.Set(reflect.ValueOf(b))
			case "int":
				i, _ := strconv.Atoi(value)
				a.Set(reflect.ValueOf(i))
			}
		}
	} else {
		//	records := base.LoadCsvCfg("E://ChatGameService2/Bin/Scp/Level.csv").Records
		file, err := os.Open(fmt.Sprintf("../Config/%s.conf", tag))
		if err != nil {
			panic(err)
		}
		defer file.Close()
		sc := bufio.NewScanner(file)
		for sc.Scan() {
			var str = sc.Text()
			var index = strings.Index(str, "=")
			if index == -1 {
				continue
			}
			var key = strings.Trim(str[0:index], " ")
			var value = strings.Trim(str[index+1:], " ")
			a := cr.FieldByName(key)
			switch a.Type().String() {
			case "string":
				value = strings.Trim(value, "\"")
				a.Set(reflect.ValueOf(value))
			case "bool":
				b, _ := strconv.ParseBool(value)
				a.Set(reflect.ValueOf(b))
			case "int":
				i, _ := strconv.Atoi(value)
				a.Set(reflect.ValueOf(i))
			}
		}
	}
	//file, err := os.Open(fmt.Sprintf("E://ChatGameService2/Bin/Config/%s.conf", tag))

}

func (s *ServerBase) initTimer() {
	s.Timer = CreateTimer()
}
