package caddyhugo

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"time"

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

	themeadditions "git.stephensearles.com/stephen/caddy-hugo2/theme-additions"
	"git.stephensearles.com/stephen/idleshut"
)

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

// Publish really renders new content into the public directory
func (ch *CaddyHugo) Publish() error {
	err := ch.persistAllEdits()
	if err != nil {
		return err
	}

	err = buildSite(ch.HugoSites)
	if err != nil {
		return err
	}

	return nil
}

func buildSite(sites *hugolib.HugoSites) error {
	err := sites.Build(hugolib.BuildCfg{ResetState: true})
	if err != nil {
		return fmt.Errorf("caddy-hugo: building site: %v", err)
	}

	return err
}

func writeThemeFiles(dir string) error {
	for _, asset := range themeadditions.AssetNames() {
		err := os.MkdirAll(path.Join(dir, filepath.Dir(asset)), 0755)
		if err != nil {
			return err
		}
		f, err := os.Create(path.Join(dir, asset))
		if err != nil {
			return err
		}
		b, err := themeadditions.Asset(asset)
		if err != nil {
			return err
		}

		_, err = f.Write(b)
		if err != nil {
			return err
		}

		err = f.Close()
		if err != nil {
			return err
		}
	}

	return nil
}

func (ch *CaddyHugo) configWithFs(fs afero.Fs) (*hugolib.HugoSites, *deps.DepsCfg, error) {
	var err error

	hfs := hugofs.NewFrom(fs, &viper.Viper{})
	cfg := &deps.DepsCfg{Fs: hfs}

	cfgPath := path.Join(ch.Dir, "config.toml")
	cfg.Cfg, _, err = hugolib.LoadConfig(hugolib.ConfigSourceDescriptor{Fs: fs, Path: cfgPath})
	if err != nil {
		return nil, cfg, fmt.Errorf("caddy-hugo: loading site configuration: %v", err)
	}
	cfg.Cfg.Set("workingDir", ch.Dir)

	sites, err := hugolib.NewHugoSites(*cfg)
	if err != nil {
		return nil, cfg, fmt.Errorf("caddy-hugo: initializing site: %v", err)
	}

	err = buildSite(sites)

	return sites, cfg, err
}

func HugoInternalProcessConfig(ch *CaddyHugo, es *editSession, touchFn func()) (idleshut.Config, error) {
	hugoSites, _, err := ch.configWithFs(es.tmpfs)
	if err != nil {
		return idleshut.Config{}, fmt.Errorf("caddy-hugo: loading site configuration: %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 = buildSite(hugoSites)
			if err != nil {
				return err
			}

			return nil
		},
	}, nil
}
