//go:build !windows

package console

import (
	"agent/commons/debug"
	"agent/modules/console/internal/utils"
	"sync"

	"github.com/google/uuid"
)

func NewConsole(uuid uuid.UUID, opts ...NewConsoleOpts) *Console {
	var o NewConsoleOpts
	if len(opts) > 0 {
		o = opts[0]
	}

	return &Console{
		uuid:          uuid,
		closeCallback: o.CloseCallback,

		command: utils.CurrentShell(),
		args:    o.Args,
		cwd:     o.Cwd,
		env:     o.Env,
		lock:    &sync.RWMutex{},

		// Каналл вмещает в себя 1024 буфера
		consoleOutput:   make(chan []byte, 1024),
		consoleCommands: make(chan CommandItem),
	}
}

func (c *Console) pipeWriter() {
	for {
		select {
		case <-c.procCtx.Done():
			return
		case command := <-c.consoleCommands:
			c.consoleOutput <- []byte("> " + command.Command + "\n")
			if command.Command[0] == 0x04 || command.Command == "^C" {
				// Ctrl+C
				c.inPipe.Write([]byte{0x03})
			} else if command.Command[0] == 0x1a || command.Command == "^Z" {
				// Ctrl+Z
				c.inPipe.Write([]byte{0x1a})
			} else {
				if _, err := c.inPipe.Write([]byte(command.Command + "\n")); err != nil {
					debug.Log(err)
					return
				}
			}
		}
	}
}
