package filter

import (
	"io/ioutil"
	"path"
	"strings"

	"gitbase.de/apairon/mark2web/pkg/logger"
	"gitbase.de/apairon/mark2web/pkg/mark2web"
	"github.com/ddliu/motto"
	"github.com/flosch/pongo2"
	_ "github.com/robertkrimen/otto/underscore"
)

// RegisterFilters reads a directory and register filters from files within it
func RegisterFilters(dir string) {
	files, err := ioutil.ReadDir(dir)
	logger.Eexit(err, "could not read from template filters dir '%s'", dir)
	for _, f := range files {
		if !f.IsDir() {
			switch path.Ext(f.Name()) {
			case ".js":
				fileBase := strings.TrimSuffix(f.Name(), ".js")
				jsFile := dir + "/" + f.Name()
				logger.D("trying to register filter from: %s", jsFile)
				/*
					jsStr, err := ioutil.ReadFile(jsFile)
					if err != nil {
						Log.Panicf("could not read '%s': %s", jsFile, err)
					}
				*/
				vm := motto.New()
				fn, err := vm.Run(jsFile)
				logger.Eexit(err, "error in javascript vm for '%s'", jsFile)
				if !fn.IsFunction() {
					logger.Exit("%s does not contain a function code", jsFile)
				}

				err = pongo2.RegisterFilter(
					fileBase,
					func(in, param *pongo2.Value) (out *pongo2.Value, erro *pongo2.Error) {
						thisObj, _ := vm.Object("({})")
						var err error
						if mark2web.CurrentContext != nil {
							err = thisObj.Set("context", *mark2web.CurrentContext)
						}

						logger.Perr(err, "could not set context in '%s': %s", jsFile)
						ret, err := fn.Call(thisObj.Value(), in.Interface(), param.Interface())
						logger.Eexit(err, "error in javascript file '%s' while calling returned function", jsFile)

						retGo, err := ret.Export()
						logger.Perr(err, "export error for '%s'", jsFile)
						return pongo2.AsValue(retGo), nil
					},
				)
				logger.Perr(err, "could not register filter from '%s'", jsFile)

			}
		}
	}

}
