package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"log"
	"math/big"
	"strings"
)

// Update operators tab-completion struct
func UpdateListenersTabCompletion() {
	// Broadcast updated listener list
	updatedListeners := GetListenerNames()
	updateMessage := fmt.Sprintf("LISTENERS_UPDATE:%s", strings.Join(updatedListeners, ","))
	SendMessageToAllOperators(updateMessage)
}

// Update operators tab-completion struct
func UpdateAgentsTabCompletion() {
	// Broadcast updated agents list
	updatedAgents := GetAgentNames()
	updateMessage := fmt.Sprintf("AGENTS_UPDATE:%s", strings.Join(updatedAgents, ","))
	SendMessageToAllOperators(updateMessage)
}

// Send message to all operators online
func SendMessageToAllOperators(message string) {
	Operators.Range(func(key, value interface{}) bool {
		id := key.(string)
		operator := value.(*Operator)

		if operator.Authenticated {
			_, err := operator.Conn.Write([]byte(message))
			if err != nil {
				debugLog("Failed to send message to operator %s (%s): %v", id, operator.OperatorIP.String(), err)
			}
			// log.Printf("Message sent to operator %s (%s)", id, operator.OperatorIP.String())
		} else {
			debugLog("Skipping unauthenticated operator %s (%s)", id, operator.OperatorIP.String())
		}

		// Return true to continue iterating
		return true
	})
}

// Get hash of password
func HashPassword(password *string) string {
	hash := sha256.Sum256([]byte(*password))
	return hex.EncodeToString(hash[:])
}

func debugLog(format string, args ...any) {
	if DevelMode {
		log.Printf(format, args...)
	}
}

func infoLog(format string, args ...any) {
	log.Printf(format, args...)
}

func encryptAES128CTR(plaintext, key, iv []byte) ([]byte, error) {
	if len(iv) != aes.BlockSize {
		return nil, errors.New("IV length must be equal to AES block size (16 bytes)")
	}
	if len(key) != 16 {
		return nil, errors.New("key length must be 16 bytes for AES-128")
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	stream := cipher.NewCTR(block, iv)
	ciphertext := make([]byte, len(plaintext))
	stream.XORKeyStream(ciphertext, plaintext)
	return ciphertext, nil
}

func encryptAES128CFB(plaintext, key, iv []byte) ([]byte, error) {
	if len(iv) != aes.BlockSize {
		return nil, errors.New("IV length must be equal to AES block size (16 bytes)")
	}
	if len(key) != 16 {
		return nil, errors.New("key length must be 16 bytes for AES-128")
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	ciphertext := make([]byte, len(plaintext))
	stream.XORKeyStream(ciphertext, plaintext)
	return ciphertext, nil
}

func TestEncryption() {
	plaintext := []byte("hello world")
	key := []byte("sWDv47xwoMkg5gJY")
	iv := []byte("6vdR2T6i7BSnpyg5")

	ciphertext, err := encryptAES128CFB(plaintext, key, iv)
	if err != nil {
		infoLog("Encryption error: %v\n", err)
		return
	}
	debugLog("Test plaintext: %s\n", plaintext)
	debugLog("Test ciphertext: ")
	for _, b := range ciphertext {
		debugLog("%02x ", b)
	}
	debugLog("\n")
}

// Generates key and IV for AES-128
func GenerateKeyAndIV() (string, string, error) {
	// Define alphanumeric character set
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	charsetLength := big.NewInt(int64(len(charset)))

	// Generate first string
	str1, err := generateString(charset, charsetLength, 16)
	if err != nil {
		return "", "", fmt.Errorf("error generating first string: %v", err)
	}

	// Generate second string
	str2, err := generateString(charset, charsetLength, 16)
	if err != nil {
		return "", "", fmt.Errorf("error generating second string: %v", err)
	}

	return str1, str2, nil
}

// Helper function to generate a random string of specified length
func generateString(charset string, charsetLength *big.Int, length int) (string, error) {
	result := make([]byte, length)
	for i := 0; i < length; i++ {
		n, err := rand.Int(rand.Reader, charsetLength)
		if err != nil {
			return "", err
		}
		result[i] = charset[n.Int64()]
	}
	return string(result), nil
}
