package main

import (
	"flag"
	"fmt"
	"os"
	"path"

	"gitbase.de/apairon/mark2web/pkg/filter"
	"gitbase.de/apairon/mark2web/pkg/logger"
	"gitbase.de/apairon/mark2web/pkg/mark2web"
	"gitbase.de/apairon/mark2web/pkg/progress"
)

var (
	// Version is the app's version string
	Version = "UNKNOWN"
	// GitHash is the current git hash for this version
	GitHash = "UNKNOWN"
	// BuildTime is the time of build of this app
	BuildTime = "UNKNOWN"
)

func main() {
	inDir := flag.String("in", "./", "input directory")
	outDir := flag.String("out", "html", "output directory")
	createOutDir := flag.Bool("create", false, "create output directory if not existing")
	//clearOutDir := flag.Bool("clear", false, "clear output directory before generating website")
	logLevel := flag.String("logLevel", "", "log level: debug, info, notice, warning, error")
	progressBars := flag.Bool("progress", false, "show progress bars for jobs")
	version := flag.Bool("version", false, "print version of this executable")

	flag.Parse()
	if version != nil && *version {
		fmt.Printf(`%11s: %s
%11s: %s
%11s: %s
`, "version", Version, "git hash", GitHash, "build time", BuildTime)
		os.Exit(0)
	}

	level := "notice"

	if progressBars != nil && *progressBars {
		progress.Start()
		level = "warning" // disable log for progressbars
	}

	if logLevel != nil && *logLevel != "" {
		level = *logLevel
	}
	logger.SetLogLevel(level)

	if inDir == nil || *inDir == "" {
		logger.Exit("input directory not specified")
	}
	iDir := path.Clean(*inDir)
	inDir = &iDir
	logger.I("input directory: %s", *inDir)

	if outDir == nil || *outDir == "" {
		logger.Exit("output directory not specified")
	}
	oDir := path.Clean(*outDir)
	outDir = &oDir
	logger.I("output directory: %s", *outDir)

	if createOutDir != nil && *createOutDir {
		if _, err := os.Stat(*outDir); os.IsNotExist(err) {
			logger.D("output directory '%s' does not exist", *outDir)
			logger.D("trying to create output directory: %s", *outDir)
			err := os.MkdirAll(*outDir, 0755)
			if err != nil {
				logger.Log.Panic(err)
			}
			logger.I("created output directory: %s", *outDir)
		} else {
			logger.I("output directory '%s' already exists", *outDir)
		}
	}

	if fD, err := os.Stat(*outDir); os.IsNotExist(err) {
		logger.Eexit(err, "output directory '%s' does not exist, try -create parameter or create manually", *outDir)
	} else {
		if fD == nil {
			logger.P("something went wrong, could not get file handle for output dir %s", *outDir)
		} else if !fD.IsDir() {
			logger.Exit("output directory '%s' is not a directory", *outDir)
		}
	}

	logger.D("reading global config...")
	configFilename := *inDir + "/config.yml"
	err := mark2web.Config.ReadFromFile(configFilename)
	if err != nil {
		logger.Eexit(err, "could not read file '%s'", configFilename)
	}
	mark2web.Config.Directories.Input = *inDir
	mark2web.Config.Directories.Output = *outDir

	logger.D("reading input directory %s", *inDir)

	defaultTemplate := "base.html"
	defaultInputFile := "README.md"
	defaultOutputFile := "index.html"
	defaultPathStrip := "^[0-9]*_(.*)"
	defaultPathIgnoreForNav := "^_"
	defaultFilenameStrip := "(.*).md$"
	defaultFilenameIgnore := "^_"
	defaultFilenameOutputExtension := "html"

	defaultPathConfig := new(mark2web.PathConfig)
	defaultPathConfig.Template = &defaultTemplate
	defaultPathConfig.Index = &mark2web.IndexConfig{
		InputFile:  &defaultInputFile,
		OutputFile: &defaultOutputFile,
	}
	defaultPathConfig.Path = &mark2web.DirnameConfig{
		Strip:        &defaultPathStrip,
		IgnoreForNav: &defaultPathIgnoreForNav,
	}
	defaultPathConfig.Filename = &mark2web.FilenameConfig{
		Strip:           &defaultFilenameStrip,
		Ignore:          &defaultFilenameIgnore,
		OutputExtension: &defaultFilenameOutputExtension,
	}
	defaultPathConfig.Imaging = &mark2web.ImagingConfig{
		Width:   1920,
		Height:  1920,
		Process: "fit",
		Quality: 75,
	}

	filtersDir := *inDir + "/templates/filters"
	if _, err := os.Stat(filtersDir); !os.IsNotExist(err) {
		filter.RegisterFilters(filtersDir)
	}

	mark2web.Run(*inDir, *outDir, defaultPathConfig)

	logger.N("done")

}
