package main

import (
	"encoding/json"
	"fmt"
	"ld/server"
	"strings"
)

func readCrew(server *server.Server) (string, error) {

	content, err := embedded.ReadFile("embed/crew.json")
	if err != nil {
		return "", err
	}

	// Create a slice to hold the parsed names
	var crewNames []string

	// Parse the JSON
	err = json.Unmarshal(content, &crewNames)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return "", err
	}

	const insertStmt = "INSERT INTO crew_member ( rank, name) VALUES (?, ?) ;"
	insstmt, err := server.StateDB.DB().Prepare(insertStmt)
	if err != nil {
		return "", err
	}
	defer insstmt.Close()

	// Print the results
	for _, text := range crewNames {
		rank, name := splitRank(text)
		if rank == "" {
			rank = "ERROR"
		}
		// fmt.Printf("%d: rank: %s name: %s\n", i+1, rank, name)
		_, err = insstmt.Exec(rank, name)
		if err != nil {
			return "", err
		}
	}
	// fmt.Println(string(content))
	return "", nil

}

// splitRank separates the rank (all tokens except the last two) from the crewman's name (last two tokens)
func splitRank(fullName string) (rank, name string) {
	tokens := strings.Fields(fullName)
	if len(tokens) < 2 {
		return fullName, "" // fallback if malformed
	}

	nameTokens := tokens[len(tokens)-2:] // last 2 tokens as name
	rankTokens := tokens[:len(tokens)-2] // everything else as rank
	name = strings.Join(nameTokens, " ")
	rank = strings.Join(rankTokens, " ")

	return rank, name
}

type Message struct {
	Timestamp string `json:"timestamp"`
	Subsystem string `json:"subsystem"`
	Severity  string `json:"severity"`
	Color     string `json:"color"`
	Message   string `json:"message"`
}

func readMessages(server *server.Server) error {
	content, err := embedded.ReadFile("embed/messages.json")
	if err != nil {
		return err
	}

	var messages []Message
	if err := json.Unmarshal(content, &messages); err != nil {
		return err
	}

	const insertStmt = "INSERT INTO ship_messages ( timestamp, subsystem, severity, color, message) VALUES (?,?,?,?,?) ;"
	insstmt, err := server.StateDB.DB().Prepare(insertStmt)
	if err != nil {
		return err
	}
	defer insstmt.Close()
	// For demonstration, print the parsed messages
	for _, m := range messages {
		// fmt.Printf("[%s] %s (%s) - %s\n", m.Timestamp, m.Subsystem, m.Severity, m.Message)
		_, err = insstmt.Exec(m.Timestamp, m.Subsystem, m.Severity, m.Color, m.Message)
		if err != nil {
			fmt.Println(err)
			return err
		}
	}

	return nil
}
