package caddyhugo

import (
	"fmt"
	"path"
	"time"

	"github.com/gohugoio/hugo/deps"
	"github.com/gohugoio/hugo/hugofs"
	"github.com/gohugoio/hugo/hugolib"
	"github.com/spf13/afero"

	"git.stephensearles.com/stephen/idleshut"
)

const (
	IdleWebsocketTimeout = 10 * time.Minute
	WebsocketFileTicker  = 1 * time.Second
)

type HugoInteractor interface {
	Render(srcdir, workdir string) HugoRenderer
}

type HugoRenderer interface {
	WriteContent(contents string) error
	Start() error
	Stop() error
}

func HugoInternalProcessConfig(ch *CaddyHugo, es *editSession, touchFn func()) (idleshut.Config, error) {

	var err error
	hugoCfg := &deps.DepsCfg{Fs: hugofs.NewFrom(es.tmpfs, ch.HugoCfg.Cfg)}
	fmt.Println(ch.Dir)
	hugoCfg.Cfg, err = hugolib.LoadConfig(es.tmpfs, "", path.Join(ch.Dir, "config.toml"))
	if err != nil {
		return idleshut.Config{}, fmt.Errorf("caddy-hugo: loading site configuration: %v", err)
	}

	hugoCfg.Cfg.Set("workingDir", ch.Dir)
	hugoSites, err := hugolib.NewHugoSites(*hugoCfg)
	if err != nil {
		return idleshut.Config{}, fmt.Errorf("caddy-hugo: initializing site: %v", err)
	}

	err = hugoSites.Build(hugolib.BuildCfg{ResetState: true})
	if err != nil {
		return idleshut.Config{}, fmt.Errorf("caddy-hugo: building site: %v", err)
	}

	return idleshut.Config{
		TickDuration: WebsocketFileTicker,
		MaxIdleTicks: uint(IdleWebsocketTimeout/WebsocketFileTicker) + 1,
		Stop: func() error {
			ch.persistEditsForSession(es)

			es.doc.Close()

			ch.mtx.Lock()
			defer ch.mtx.Unlock()
			delete(ch.docs, es.filename)

			return nil
		},
		TickError: func(err error) {
			fmt.Println("error processing draft:", err)
		},
		Tick: func() error {
			err := afero.WriteFile(es.tmpfs, es.filename, []byte(es.doc.Contents()), 0644)
			if err != nil {
				return err
			}

			err = hugoSites.Build(hugolib.BuildCfg{ResetState: true})
			if err != nil {
				return err
			}

			return nil
		},
	}, nil
}
