package caddyhugo

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"os"
	"path"

	"github.com/gohugoio/hugo/deps"
	"github.com/gohugoio/hugo/hugofs"
	"github.com/gohugoio/hugo/hugolib"
	"github.com/mholt/caddy"
	"github.com/mholt/caddy/caddyhttp/httpserver"
)

func (ch *CaddyHugo) SetupCaddy(c *caddy.Controller) error {
	ch.Site = httpserver.GetConfig(c)
	err := ch.Setup(ch.Site.Root)
	ch.Site.AddMiddleware(ch.Middleware(c))
	return err
}

func (ch *CaddyHugo) Setup(dir string) error {
	var err error

	ch.Dir = dir
	ch.docs = make(map[string]*editSession)

	ch.HugoCfg = &deps.DepsCfg{}

	ch.HugoCfg.Cfg, err = hugolib.LoadConfig(hugofs.Os, dir, "")
	if err != nil {
		return fmt.Errorf("error loading hugo config: %v", err)
	}

	ch.HugoCfg.Cfg.Set("workingdir", dir)
	ch.HugoSites, err = hugolib.NewHugoSites(*ch.HugoCfg)
	if err != nil {
		return fmt.Errorf("error intializing hugo: %v", err)
	}

	err = ch.Build()
	if err != nil {
		return fmt.Errorf("error building initial hugo: %v", err)
	}

	ch.authorTmpl, err = template.New("").Parse(AuthorPage)
	if err != nil {
		return fmt.Errorf("author template invalid: %v", err)
	}

	ch.adminTmpl, err = template.New("").Parse(AdminPage)
	if err != nil {
		return fmt.Errorf("admin template invalid: %v", err)
	}

	ch.editTmpl, err = template.New("").Parse(EditPage)
	if err != nil {
		return fmt.Errorf("edit template invalid: %v", err)
	}

	thumbDir, err := ioutil.TempDir("", "thumbs")
	if err != nil {
		return fmt.Errorf("couldn't initialize media: %v", err)
	}

	ch.Media = &MediaSource{
		StorageDir: path.Join(dir, "media"),
		ThumbDir:   thumbDir,
	}

	err = os.MkdirAll(ch.Media.StorageDir, 0755)
	if err != nil {
		return fmt.Errorf("couldn't initialize media: %v", err)
	}

	err = ch.Publish()
	if err != nil {
		fmt.Println("error with initial publish of hugo site:", err)
	}

	return nil
}
