package main

import (
	"fmt"
	"io"
	"path/filepath"
	"strconv"
	"strings"
)

const (
	sheetLines = 30
	measure    = 71 // runes after the one column margin; 72 in all
)

var cutLine = strings.Repeat("- ", 34) + "cut"

func printSlips(book, nArg string, out, errw io.Writer) error {
	b, err := readBook(book)
	if err != nil {
		return err
	}
	sc, err := readSidecar(sidecarPath(book))
	if err != nil {
		return err
	}
	var entries [][]string
	notFit := 0
	for _, s := range ordered(sc) {
		if nArg != "" && strconv.Itoa(s.N) != nArg {
			continue
		}
		if s.Withdrawn != "" {
			if nArg != "" {
				return refuse("Slip %d is withdrawn.", s.N)
			}
			continue
		}
		st, l := locate(b, s)
		if st == gone {
			notFit++
			continue
		}
		entries = append(entries, entry(s, st, l))
	}
	if notFit > 0 {
		msg := fmt.Sprintf("%d slips not printed: they no longer fit.", notFit)
		if notFit == 1 {
			msg = "1 slip not printed: it no longer fits."
		}
		if nArg != "" {
			return refusal(msg)
		}
		fmt.Fprintln(errw, msg)
	}
	if nArg != "" && len(entries) == 0 {
		return refuse("%s has no slip %s.", clean(book), clean(nArg))
	}
	if len(entries) == 0 {
		if live(sc) == 0 {
			fmt.Fprintf(errw, "No slips for %s.\n", clean(book))
		}
		return nil
	}
	for _, line := range sheets(filepath.Base(book), b.Edition[:12], today(), entries) {
		fmt.Fprintln(out, line)
	}
	return nil
}

// entry is one slip's lines on the sheet: the quoted line, the edition line when it applies, the note.
func entry(s Slip, st state, line int) []string {
	num := strconv.Itoa(s.N) + ". "
	ind := len(num)
	width := measure - ind
	head := fmt.Sprintf("Line %d%s: \"%s\"", line, writtenAt(line, s.Line), quote(s.Text))
	paras := []string{head}
	if st == moved {
		paras = append(paras, "Edition differs; line still fits.")
	}
	paras = append(paras, clean(s.Note))
	var out []string
	for _, p := range paras {
		for _, l := range wrap(p, width) {
			lead := strings.Repeat(" ", ind)
			if len(out) == 0 {
				lead = num
			}
			out = append(out, " "+lead+l)
		}
	}
	return out
}

// sheets lays the entries out on 30 line sheets; one entry never spans two.
func sheets(base, ed, date string, entries [][]string) []string {
	name := clean(base)
	if r := []rune(name); len(r) > 30 {
		name = string(r[:27]) + "..."
	}
	closing := wrap(fmt.Sprintf("This slip belongs to edition %s of %s and to no other.", ed, name), measure)
	room := sheetLines - 2 - 5 - 1 - len(closing) // cut lines, heading block, gap, closing
	var bodies [][]string
	var body []string
	for _, e := range entries {
		need := len(e)
		if len(body) > 0 {
			need++
		}
		if len(body) > 0 && len(body)+need > room {
			bodies = append(bodies, body)
			body = nil
		}
		if len(body) > 0 {
			body = append(body, "")
		}
		body = append(body, e...)
	}
	bodies = append(bodies, body)
	var out []string
	for k, body := range bodies {
		header := " ERRATA"
		if len(bodies) > 1 {
			header = fmt.Sprintf(" ERRATA, slip sheet %d of %d", k+1, len(bodies))
		}
		out = append(out, cutLine, header, fmt.Sprintf(" %s   ed. %s   printed %s", name, ed, date), "",
			" Please correct the following before use.", "")
		out = append(out, body...)
		for i := len(body); i < room; i++ {
			out = append(out, "")
		}
		out = append(out, "")
		for _, c := range closing {
			out = append(out, " "+c)
		}
		out = append(out, cutLine)
	}
	return out
}

// wrap breaks s at spaces into lines of at most w runes; a longer word is broken hard at w.
func wrap(s string, w int) []string {
	r := []rune(s)
	var out []string
	for len(r) > w {
		cut := -1
		for i := w; i > 0; i-- {
			if r[i] == ' ' {
				cut = i
				break
			}
		}
		line := ""
		if cut > 0 {
			line = strings.TrimRight(string(r[:cut]), " ")
		}
		if line == "" {
			out = append(out, string(r[:w]))
			r = r[w:]
			continue
		}
		out = append(out, line)
		r = r[cut:]
		for len(r) > 0 && r[0] == ' ' {
			r = r[1:]
		}
	}
	return append(out, string(r))
}
