package modem

import (
	"fmt"
	"log"
	"strings"

	"go.bug.st/serial"
)

func (m *modem) makeAtReq(msg string) (string, error) {
	log.Println("Write...")
	if _, err := m.serialPort.Write([]byte(msg)); err != nil {
		return "", fmt.Errorf("serial port write: %w", err)
	}
	log.Println("Read...")
	readLen, err := m.serialPort.Read(m.inputBuf)
	if err != nil {
		return "", fmt.Errorf("port read: %w", err)
	}
	return strings.Split(string(m.inputBuf[:readLen]), "\n")[1], nil
}

func (m *modem) makeAtEchoReqAndCheck(msg, checkMsg string) (bool, error) {
	ans, err := m.makeAtReq(msg)
	log.Println(msg, checkMsg)
	if err != nil {
		return false, err
	}
	return (len(ans) >= len(checkMsg) && ans[:len(checkMsg)] == checkMsg), nil
}

func (m *modem) connect(port string) error {
	log.Println("Connecting to", port, "...")
	s, err := serial.Open(port, &serial.Mode{BaudRate: m.baudrate})
	if err != nil {
		return fmt.Errorf("open port: %w", err)
	}
	// s.Close() There is no open f
	// s.Open()
	m.serialPort = s
	return nil
}

func (m *modem) disconnect() error {
	defer func() {
		m.serialPort = nil
	}()
	if err := m.serialPort.Close(); err != nil {
		return fmt.Errorf("close port: %w", err)
	}
	return nil
}
