package main

import (
	"fmt"
	"strings"

	"go.wit.com/lib/protobuf/chatpb"
	"go.wit.com/log"
)

func doPlayback() {
	if argv.Playback.Uuid != "" {
		showChat(argv.Playback.Uuid)
		return
	}

	listChats(me.chats)
}

func showChat(uuid string) {
	chat := me.chats.FindByUuid(uuid)
	if chat == nil {
		log.Info("unknown uuid", uuid)
		return
	}
	prettyFormatChat(chat)
}

func listChats(chats *chatpb.Chats) {
	if argv.Playback.Long != nil {
		for _, chat := range chats.GetChats() {
			listEntries(chat)
		}
		return
	}

	log.Infof("Found %d chat topic(s) in the log.", len(chats.GetChats()))
	fmt.Println("-------------------------------------------------")

	for _, chat := range chats.GetChats() {
		entryCount := len(chat.GetEntries())
		var formattedTime string
		if ctime := chat.GetCtime(); ctime != nil {
			t := ctime.AsTime()
			formattedTime = t.Format("2006-01-02 15:04:05")
		} else {
			formattedTime = "No Timestamp"
		}

		fmt.Printf("Topic: %-25s | Entries: %-4d | Started: %s | UUID: %s\n",
			chat.GetChatName(),
			entryCount,
			formattedTime,
			chat.GetUuid(),
		)
	}
	fmt.Println("-------------------------------------------------")
}

// print out one line for each chat entry
func listEntries(chat *chatpb.Chat) {
	fmt.Printf("--- Entries for Topic: %s ---\n", chat.GetChatName())
	width := getTerminalWidth()

	// Determine the maximum length of the author and time string
	maxAuthorAndTimeLen := 0
	for _, entry := range chat.GetEntries() {
		author := entry.GetFrom().String()
		var formattedTime string
		if ctime := entry.GetCtime(); ctime != nil {
			t := ctime.AsTime()
			formattedTime = t.Format("2006-01-02 15:04:05")
		} else {
			formattedTime = "No Time"
		}
		authorAndTime := fmt.Sprintf("[%s] (%s)", author, formattedTime)
		if len(authorAndTime) > maxAuthorAndTimeLen {
			maxAuthorAndTimeLen = len(authorAndTime)
		}
	}

	for _, entry := range chat.GetEntries() {
		author := entry.GetFrom().String()
		var formattedTime string
		if ctime := entry.GetCtime(); ctime != nil {
			t := ctime.AsTime()
			formattedTime = t.Format("2006-01-02 15:04:05")
		} else {
			formattedTime = "No Time"
		}

		// Create a short preview of the content
		contentPreview := strings.TrimSpace(entry.GetContent())
		// Replace newlines with spaces for a clean one-line view
		contentPreview = strings.ReplaceAll(contentPreview, "\n", " ")

		authorAndTime := fmt.Sprintf("[%s] (%s)", author, formattedTime)

		availableWidth := width - maxAuthorAndTimeLen - 1 // -1 for a space
		if len(contentPreview) > availableWidth {
			contentPreview = contentPreview[:availableWidth-3] + "..."
		}

		if author == "USER" {
			// Calculate padding to fill the space between content and the right-aligned author/time
			padding := width - len(contentPreview) - maxAuthorAndTimeLen
			if padding < 0 {
				padding = 0
			}
			// Calculate padding to align the author/time string itself
			authorAndTimePadding := maxAuthorAndTimeLen - len(authorAndTime)
			if authorAndTimePadding < 0 {
				authorAndTimePadding = 0
			}
			fmt.Printf("%s%s%s%s\n", contentPreview, strings.Repeat(" ", padding), strings.Repeat(" ", authorAndTimePadding), authorAndTime)
		} else {
			padding := maxAuthorAndTimeLen - len(authorAndTime)
			if padding < 0 {
				padding = 0
			}
			fmt.Printf("%s%s %s\n", authorAndTime, strings.Repeat(" ", padding), contentPreview)
		}
	}
	fmt.Println("-------------------------------------------------")
}
