package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func PrintMenu() {
	fmt.Printf("\n\n### TODO APP ###\n")
	fmt.Printf("1: List Todo\n")
	fmt.Printf("2: Add Todo\n")
	fmt.Printf("3: Remove Todo (via index)\n")
	fmt.Printf("4: Save to file\n")

	fmt.Printf("\n\n0: Quit\n> ")

}

const (
	QUIT   = 0
	LIST   = 1
	ADD    = 2
	REMOVE = 3
	SAVE   = 4
)

func main() {
	fmt.Print("\033[H\033[2J") //clear
	PrintMenu()
	list := Todos{}
	for {

		var input int
		n, err := fmt.Scanln(&input)
		if n < 1 || err != nil {
			fmt.Print("[ERR] Invalid input\n")
		}

		switch input {
		case QUIT:
			fmt.Print("Quitting, goodbye!\n")
			os.Exit(0)
		case LIST:
			if err := list.ListTodo(); err != nil {
				fmt.Print(err)
			}
			PrintMenu()
		case ADD:
			in := bufio.NewReader(os.Stdin)

			fmt.Print("Add Title:\n> ")
			title, _ := in.ReadString('\n')

			fmt.Print("Add Content:\n> ")
			content, _ := in.ReadString('\n')

			list.AddTodo(Todo{Title: title, Content: content})
			fmt.Printf("Added %s to the list!\n", title)
			PrintMenu()
		case REMOVE:
			var index int
			fmt.Printf("Which TODO to remove?\n> ")

			if _, err := fmt.Scanf("%d", &index); err != nil {
				fmt.Printf("Which TODO to remove?\n> ")
			}

			if err := list.RemoveTodo(index); err != nil {
				fmt.Print(err)
			}
			PrintMenu()
		case SAVE:
			in := bufio.NewReader(os.Stdin)
			fmt.Print("Save to file:\n> ")
			filename, _ := in.ReadString('\n')
			filename = strings.TrimSuffix(filename, "\n")

			if err := list.SaveToFile(filename); err != nil {
				fmt.Print(err)
			} else {
				fmt.Printf("%s saved!\n", filename)
			}
			PrintMenu()
		default:
			PrintMenu()
		}
	}
}
