package utils

import (
	"fmt"
	"log"
	"strings"

	"gitea.unprism.ru/KRBL/sim-modem/api/modem/at"
)

func CheckPIN(port at.Port, logger *log.Logger) error {
	// Get code
	resp, err := port.Send("AT+CPIN?")
	if err != nil {
		return fmt.Errorf("AT+CPIN? request: %w", err)
	}
	if !resp.Check() || !resp.CheckFront("+CPIN:") {
		return fmt.Errorf("AT+CPIN? error response: %s", resp)
	}
	code := strings.ReplaceAll(strings.ReplaceAll(strings.Split(resp.RmFront("+CPIN:").String(), "\n")[0], "\r", ""), " ", "")
	if code != "READY" {
		return fmt.Errorf("not READY code: %s", code)
	}
	logger.Println("PIN is ready")
	return nil
}