//go:build !windows
// +build !windows

package editor

import (
	
	
	
	
	
	
	
	
	
)

var (
	// ErrNoTempDirectory indicates that Go's standard os.TempDir() did not return a directory.
	ErrNoTempDirectory = errors.New("could not identify the temp directory on this system")
	// ErrWrite indicates that we failed to write the buffer to the file.
	ErrWrite = errors.New("failed to write buffer to file")
	// ErrCreate indicates that we failed to create the temp buffer file.
	ErrCreate = errors.New("failed to create buffer file")
	// ErrOpen indicates that we failed to open the buffer file.
	ErrOpen = errors.New("failed to open buffer file")
	// ErrRemove indicates that we failed to delete the buffer file.
	ErrRemove = errors.New("failed to remove buffer file")
	// ErrRead indicates that we failed to read the buffer file's content.
	ErrRead = errors.New("failed to read buffer file")
)

func writeToFile( []byte,  string) (string, error) {
	var  string

	// Get the temp directory, or fail.
	 := os.TempDir()
	if  == "" {
		return "", ErrNoTempDirectory
	}

	// If the user has not provided any filename (including an extension)
	// we generate a random filename with no extension.
	if  == "" {
		 := strconv.Itoa(time.Now().Nanosecond()) + ":" + string()

		 := md5.New()

		,  := .Write([]byte())
		if  != nil {
			return "", 
		}

		 := "readline-" + hex.EncodeToString(.Sum(nil)) + "-" + strconv.Itoa(os.Getpid())
		 = filepath.Join(, )
	} else {
		// Else, still use the temp/ dir, but with the provided filename
		 = filepath.Join(, )
	}

	,  := os.Create()
	if  != nil {
		return "", fmt.Errorf("%w: %s", ErrCreate, .Error())
	}

	defer .Close()

	_,  = .Write()
	if  != nil {
		return "", fmt.Errorf("%w: %s", ErrWrite, .Error())
	}

	return , nil
}

func readTempFile( string) ([]byte, error) {
	,  := os.Open()
	if  != nil {
		return nil, fmt.Errorf("%w: %s", ErrOpen, .Error())
	}

	,  := io.ReadAll()
	if  != nil {
		return nil, fmt.Errorf("%w: %s", ErrRead, .Error())
	}

	if len() > 0 && [len()-1] == '\n' {
		 = [:len()-1]
	}

	if len() > 0 && [len()-1] == '\r' {
		 = [:len()-1]
	}

	if len() > 0 && [len()-1] == '\n' {
		 = [:len()-1]
	}

	if len() > 0 && [len()-1] == '\r' {
		 = [:len()-1]
	}

	if  = os.Remove();  != nil {
		return nil, fmt.Errorf("%w: %s", ErrRemove, .Error())
	}

	return , nil
}

func getSystemEditor( bool) ( string) {
	 = os.Getenv("VISUAL")
	if  == "" {
		return
	}

	 = os.Getenv("EDITOR")
	if  == "" {
		return
	}

	if  {
		return "emacs"
	}

	return "vi"
}