package cluster

import (
	"fmt"
	"io"
	"os"
	"path/filepath"

	fs "github.com/hack-pad/hackpadfs"
)

// OpenFile opens a file on the machine's config directory with the specified flags
func (m *Machine) OpenFile(name string, flags int, args ...any) (fs.File, error) {
	fullName := m.getFilename(name, args...)

	return m.zone.zones.OpenFile(fullName, flags)
}

// CreateTruncFile creates or truncates a file on the machine's config directory
func (m *Machine) CreateTruncFile(name string, args ...any) (io.WriteCloser, error) {
	return m.openWriter(name, os.O_CREATE|os.O_TRUNC, args...)
}

// CreateFile creates a file on the machine's config directory
func (m *Machine) CreateFile(name string, args ...any) (io.WriteCloser, error) {
	return m.openWriter(name, os.O_CREATE, args...)
}

func (m *Machine) openWriter(name string, flags int, args ...any) (io.WriteCloser, error) {
	f, err := m.OpenFile(name, os.O_WRONLY|flags, args...)
	if err != nil {
		return nil, err
	}

	if f, ok := f.(io.WriteCloser); ok {
		return f, nil
	}

	panic("unreachable")
}

// RemoveFile deletes a file from the machine's config directory
func (m *Machine) RemoveFile(name string, args ...any) error {
	fullName := m.getFilename(name, args...)

	return m.zone.zones.RemoveFile(fullName)
}

// ReadFile reads a file from the machine's config directory
func (m *Machine) ReadFile(name string, args ...any) ([]byte, error) {
	fullName := m.getFilename(name, args...)

	return m.zone.zones.ReadFile(fullName)
}

// ReadLines reads a file from the machine's config directory,
// split by lines, trimmed, and accepting `#` to comment lines out.
func (m *Machine) ReadLines(name string, args ...any) ([]string, error) {
	fullName := m.getFilename(name, args...)

	return m.zone.zones.ReadLines(fullName)
}

// WriteStringFile writes the given content to a file on the machine's config directory
func (m *Machine) WriteStringFile(value string, name string, args ...any) error {
	fullName := m.getFilename(name, args...)

	return m.zone.zones.WriteStringFile(value, fullName)
}

// MkdirAll creates directories relative to the machine's config directory
func (m *Machine) MkdirAll(name string, args ...any) error {
	fullName := m.getFilename(name, args...)

	return m.zone.zones.MkdirAll(fullName)
}

func (m *Machine) getFilename(name string, args ...any) string {
	if len(args) > 0 {
		name = fmt.Sprintf(name, args...)
	}

	s := []string{
		m.zone.Name,
		m.Name,
		name,
	}

	return filepath.Join(s...)
}