/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"

	"github.com/jawher/mow.cli"

	"ecload/pkg/ecload"
)

// Initialize logger formats.
func initLogger(
	traceHandle io.Writer,
	infoHandle io.Writer,
	warningHandle io.Writer,
	errorHandle io.Writer) ecload.Logger {

	return ecload.Logger{
		Trace:   log.New(traceHandle, "TRACE: ", log.Ldate|log.Ltime),
		Info:    log.New(infoHandle, "INFO: ", log.Ldate|log.Ltime),
		Warning: log.New(warningHandle, "WARNING: ", log.Ldate|log.Ltime),
		Error:   log.New(errorHandle, "ERROR: ", log.Ldate|log.Ltime),
	}
}

func main() {
	logger := initLogger(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)

	app := cli.App("ecload", "Download books from https://www.e-codices.unifr.ch")
	app.Version("v version", "0.1.0")

	app.Spec = "[-o=<PATH>] [-s=<SIZE>] ID"

	var (
		outDir = app.StringOpt("o out-dir", ".", "save pdf in PATH")
		size   = app.StringOpt("s size", "medium", "Size of the downloaded images. One of small, medium, large, max.")
		id     = app.StringArg("ID", "", "ID of the book to download. Copy the last two url parts on the overview page to get it (for example bbb/0003).")
	)

	app.Action = func() {
		if *size != "small" && *size != "medium" && *size != "large" && *size != "max" {
			logger.Error.Println("SIZE must be one of: small, medium, large, max")
			cli.Exit(1)
		}

		err := ecload.DownloadBook(*outDir, *size, *id, logger)
		if err != nil {
			logger.Error.Println(err)
		}
	}

	app.Run(os.Args)
}
