package miningsoft

import (
	"bufio"
	"log"
	"os/exec"
	"path/filepath"
	"strings"
)

/*
XTM - Cuckaroo29 - lolMiner.exe --algo CR29 --pool xtm-c29.kryptex.network:7040 --user WALLET_ADDRESS/WORKER_NAME
CFX - Conflux - lolMiner.exe --algo OCTOPUS --pool cfx.kryptex.network:7027 --user WALLET_ADDRESS/WORKER_NAME
IRON - IronFish - lolMiner.exe --algo FISHHASH --pool iron.kryptex.network:7017 --user WALLET_ADDRESS.WORKER_NAME
NEXA - NexaPow - lolMiner.exe --algo NEXA --pool nexa.kryptex.network:7026 --user WALLET_ADDRESS/WORKER_NAME
KLS - Karlsen - lolMiner.exe --algo KARLSENV2 --pool kls.kryptex.network:7022 --user WALLET_ADDRESS/WORKER_NAME
ERG - Autolykos - lolMiner.exe --algo AUTOLYKOS2 --pool erg.kryptex.network:7021 --user WALLET_ADDRESS/WORKER_NAME
XEL - Xelishashv2 - rigel.exe -a xelishashv2 -o stratum+tcp://xel.kryptex.network:7019 -u WALLET_ADDRESS/WORKER_NAME
QUAI - QUAI - rigel.exe -a quai -o stratum+tcp://quai.kryptex.network:7035 -u WALLET_ADDRESS/WORKER_NAME
XNA - Neurai - rigel.exe -a kawpow --coin xna -o stratum+tcp://xna.kryptex.network:7024 -u WALLET_ADDRESS/WORKER_NAME
CLORE - KawPow - rigel.exe -a kawpow --coin clore -o stratum+tcp://clore.kryptex.network:7025 -u WALLET_ADDRESS/WORKER_NAME
RVN - Ravencoin - rigel.exe -a kawpow --coin rvn -o stratum+tcp://rvn.kryptex.network:7031 -u WALLET_ADDRESS/WORKER_NAME
*/

const SOFTNAME = "lolMiner"

func StartMiner(soft_path, algo, pool, user, worker_id string, ch chan string) {
	name := filepath.Join(soft_path, SOFTNAME)
	args := []string{"--algo", algo, "--pool", pool, "--user", user + "/" + worker_id}

	cmd := exec.Command(name, args...)
	cmd.Dir = soft_path

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Printf("获取 lolMiner 标准输出失败: %v", err)
		return
	}
	// stderr, err := cmd.StderrPipe()
	// if err != nil {
	// 	log.Printf("获取 lolMiner 错误输出失败: %v", err)
	// 	return
	// }
	log.Printf("执行命令：%s %s", name, strings.Join(args, " "))
	// 启动lolminer
	err = cmd.Start()
	if err != nil {
		log.Printf("Error starting lolMiner: %v", err)
		return
	}

	// 处理标准输出
	go func() {
		scanner := bufio.NewScanner(stdout)
		for scanner.Scan() {
			line := scanner.Text()
			switch {
			case strings.Contains(line, "Lost connection to stratum"):
				log.Printf("lolMiner 检测到矿池断开连接: %s", line)
			case strings.Contains(line, "Average speed (15s)"):
				if strings.Contains(line, "Average speed (15s): 0.00 Mh/s") {
					log.Printf("lolMiner 检测到没有算力: %s", line)
				} else {
					// 有算力
				}
			case strings.Contains(line, "defect stratum message"):
				log.Printf("lolMiner 检测到 stratum 协议错误: %s", line)

			default:
				log.Printf("lolMiner 输出: %s", line)
			}
		}
		if err := scanner.Err(); err != nil {
			log.Printf("读取 lolMiner 标准输出失败: %v", err)
		}
	}()
}
