package src

import (
	message "client/internal/msg"
	"fmt"
	"log"
	"sync"
)

type OS interface {
	GetGPUInfo() (map[int]message.GPU, error)
	Mining(cfg message.ConfigurationMiningMsg) error
	StopMining()
	GetMACAddress() (string, error)
}

type SystemServer struct {
	mu      sync.Mutex
	systems map[string]OS
}

func NewSystemServer() *SystemServer {
	return &SystemServer{
		systems: make(map[string]OS),
	}
}

func (s *SystemServer) ResiterSystem(name string, os OS) {
	s.mu.Lock()
	s.systems[name] = os
	s.mu.Unlock()
}

func (s *SystemServer) GetGPUInfo(osName string) (map[int]message.GPU, error) {
	if srv, ok := s.systems[osName]; ok {
		gpus, err := srv.GetGPUInfo()
		if err != nil {
			return map[int]message.GPU{}, fmt.Errorf("获取操作系统(%s)GPU信息失败：%v", osName, err)
		}
		return gpus, nil
	}
	return map[int]message.GPU{}, fmt.Errorf("错误的操作系统：%s", osName)
}

func (s *SystemServer) Mining(osName string, cfg message.ConfigurationMiningMsg) error {
	if srv, ok := s.systems[osName]; ok {
		err := srv.Mining(cfg)
		if err != nil {
			return fmt.Errorf("开始挖矿失败：%v", err)
		}
		return nil
	}
	return fmt.Errorf("错误的操作系统：%s", osName)
}

func (s *SystemServer) GetMACAddress(osName string) (string, error) {
	if srv, ok := s.systems[osName]; ok {
		mac, err := srv.GetMACAddress()
		if err != nil {
			return "", fmt.Errorf("获取当前机器MAC码失败")
		}
		return mac, nil
	}
	return "", fmt.Errorf("错误的操作系统：%s", osName)
}

func (s *SystemServer) StopMining(osName string) {
	if srv, ok := s.systems[osName]; ok {
		srv.StopMining()
	} else {
		log.Printf("错误的操作系统：%s", osName)
	}
}
