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 "scan" and nothing else. "quarantine" moves files, so it is
// deliberately not offered here, not even as a dry run, and no flag that makes
// this program write to disk appears anywhere in this file.
func runGuided() {
	in := bufio.NewScanner(os.Stdin)

	fmt.Println()
	fmt.Println("  MediaRescue")
	fmt.Println("  Check a folder of photos and tell you which ones are damaged.")
	fmt.Println()
	fmt.Println("  Every .jpg, .png and .gif is opened and decoded all the way to the")
	fmt.Println("  last pixel, so a photo that looks fine in a thumbnail but is really")
	fmt.Println("  half-written is caught. Each one gets a one-word verdict.")
	fmt.Println()
	fmt.Println("  It only reads. Nothing is moved, changed or deleted.")
	fmt.Println()

	folder, ok := askFolder(in)
	if !ok {
		return
	}

	fmt.Println()
	fmt.Println("  Working. Decoding every picture takes a moment on a big library.")
	fmt.Println()
	runScan([]string{"--recursive", folder})

	fmt.Println()
	fmt.Println("  Done. Nothing on your disk was changed.")
	fmt.Println("  The command-line version can also move the damaged ones out of the")
	fmt.Println("  way into a folder of your choosing: mediarescue --help")
	pause(in)
}

// askFolder asks for the photo folder and keeps asking until the answer is a
// folder that really exists. It reports false only when stdin closes, at which
// point there is nothing sensible left to ask.
func askFolder(in *bufio.Scanner) (string, bool) {
	suggested := suggestedFolder()
	for {
		fmt.Println("  Which folder of photos shall I check?")
		if suggested != "" {
			fmt.Printf("  (press Enter for %s)\n", suggested)
		}
		fmt.Print("  > ")

		if !in.Scan() {
			return "", false
		}
		answer := strings.TrimSpace(in.Text())
		answer = strings.Trim(answer, `"`)
		if answer == "" {
			answer = suggested
		}
		if answer == "" {
			fmt.Println()
			fmt.Println("  I need a folder to look at. 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 single file, not a folder. Give me the folder it sits\n", answer)
			fmt.Println("  in and I will check everything inside.")
			fmt.Println()
			continue
		}
		return answer, true
	}
}

// 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 ""
	}
	// Pictures is where a photo library lives on every mainstream system.
	for _, name := range []string{"Pictures", "Downloads"} {
		candidate := filepath.Join(home, name)
		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()
}
