package main

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// runGuided is what happens when somebody double-clicks the program instead of
// typing its name at a prompt.
//
// Without this, Explorer opens a console, main() finds no arguments, prints
// the usage text to stderr and exits — and Windows destroys the window in the
// same instant. From the other side of the screen that is indistinguishable
// from a crash. So when we know we were double-clicked, we ask the one
// question the program actually needs and stay on screen until the reader is
// done.
//
// This path is entered ONLY when there are no arguments and both ends of the
// program are a real console. Any scripted or piped use takes exactly the same
// code path it always did.
//
// Guided mode runs "validate", which is the read-only half of DocSnap: it
// reports what a document built from this folder would be missing, without
// generating a single file. Building writes documents into a folder of its
// own, so that stays on the command line.
func runGuided() {
	in := bufio.NewScanner(os.Stdin)

	fmt.Println()
	fmt.Println("  DocSnap")
	fmt.Println("  Turn a folder of screenshots into a step-by-step guide.")
	fmt.Println()
	fmt.Println("  Each screenshot becomes a numbered step, and the words under each")
	fmt.Println("  step come from a plain text file called captions.txt sitting beside")
	fmt.Println("  the pictures. Right now I will check a folder for you: how many")
	fmt.Println("  screenshots are in it, and which ones still have nothing written")
	fmt.Println("  about them.")
	fmt.Println()
	fmt.Println("  This only looks. No document is generated and no file is changed.")
	fmt.Println()

	suggested := suggestedFolder()
	for {
		fmt.Println("  Which folder of screenshots shall I check?")
		if suggested != "" {
			fmt.Printf("  (press Enter for %s)\n", suggested)
		}
		fmt.Print("  > ")

		if !in.Scan() {
			// stdin closed on us; there is nothing sensible left to ask.
			return
		}
		answer := strings.TrimSpace(in.Text())
		answer = strings.Trim(answer, `"`)
		if answer == "" {
			answer = suggested
		}
		if answer == "" {
			fmt.Println()
			fmt.Println("  I need a folder to check. Try again, or close this window.")
			fmt.Println()
			continue
		}

		info, err := os.Stat(answer)
		switch {
		case err != nil:
			fmt.Println()
			fmt.Printf("  I cannot find %q.\n", answer)
			fmt.Println("  Tip: you can drag a folder from Explorer onto this window to")
			fmt.Println("  paste its location, then press Enter.")
			fmt.Println()
			continue
		case !info.IsDir():
			fmt.Println()
			fmt.Printf("  %q is a file, not a folder. Give me the folder it sits in.\n", answer)
			fmt.Println()
			continue
		}

		// validate treats a folder with no pictures in it as an error and
		// stops. Say it in plain words first, so the reader gets another go.
		images, err := findImages(answer)
		if err != nil {
			fmt.Println()
			fmt.Printf("  I cannot read what is inside %q.\n", answer)
			fmt.Println("  Try a folder you have permission to open.")
			fmt.Println()
			continue
		}
		if len(images) == 0 {
			fmt.Println()
			fmt.Printf("  There are no pictures directly inside %q.\n", answer)
			fmt.Println("  DocSnap looks for .png, .jpg and the like in the folder itself,")
			fmt.Println("  not in sub-folders. Try the folder the screenshots are in.")
			fmt.Println()
			continue
		}

		fmt.Println()
		cmdValidate([]string{answer})
		break
	}

	fmt.Println()
	fmt.Println("  Done. Nothing was written.")
	fmt.Println("  Add a captions.txt next to the screenshots — one line per picture,")
	fmt.Println("  in the form  filename.png: what this step does  — then build the")
	fmt.Println("  finished document with the command-line version: docsnap help")
	pause(in)
}

// suggestedFolder offers somewhere worth checking that is certain to exist, so
// the reader can get a useful answer by pressing one key.
func suggestedFolder() string {
	home, err := os.UserHomeDir()
	if err != nil {
		return ""
	}
	// Windows drops screenshots into Pictures\Screenshots by default, which is
	// exactly the folder somebody documenting a procedure ends up with.
	for _, rel := range []string{
		filepath.Join("Pictures", "Screenshots"),
		"Pictures",
		"Desktop",
	} {
		candidate := filepath.Join(home, rel)
		if info, err := os.Stat(candidate); err == nil && info.IsDir() {
			return candidate
		}
	}
	return home
}

// pause keeps the console window open. Explorer closes it the moment the
// process exits, so without this the reader never sees the output.
func pause(in *bufio.Scanner) {
	fmt.Println()
	fmt.Print("  Press Enter to close this window. ")
	in.Scan()
}
