package main

import (
	"flow"
	"flowserver"
	"fmt"
	"log"
	"math/rand"
	"strings"
	"time"

	"github.com/gohxs/prettylog"
)

func main() {
	prettylog.Global()

	log.Println("Running version:", flowserver.Version)

	flow.Register("str.cat", strCat)
	flow.Register("str.reverse", strReverse)
	flow.Register("str.split", strings.Split)
	flow.Register("str.join", strings.Join)

	flow.Register("delay.reverse", delayReverse)
	flow.Register("delay.split", delaySplit)
	flow.Register("delay.join", delayJoin)
	flow.Register("duration", duration)

	f := flowserver.FlowServer{}
	f.ListenAndServe()
}

/* Sample funcs */
func strCat(a1, a2 string) string {
	return a1 + a2
}

func strReverse(s string) string {
	n := len(s)
	runes := make([]rune, n)
	for _, r := range s {
		n--
		runes[n] = r
	}
	return string(runes[n:])
}

func delayCat(a1, a2 string) string {
	time.Sleep(time.Duration(2+rand.Intn(10)) * time.Second) // Simulate
	return strCat(a1, a2)
}

func delayReverse(s string) string {
	time.Sleep(time.Duration(2+rand.Intn(10)) * time.Second) // Simulate
	return strReverse(s)

}
func delaySplit(s, sep string) []string {
	time.Sleep(time.Duration(2+rand.Intn(10)) * time.Second) // Simulate
	return strings.Split(s, sep)
}
func delayJoin(s []string, join string) string {
	time.Sleep(time.Duration(2+rand.Intn(10)) * time.Second) // Simulate
	return strings.Join(s, join)
}

func duration(s string) string {
	mark := time.Now()
	time.Sleep(time.Duration(2+rand.Intn(10)) * time.Second) // Simulate
	now := time.Now()

	return s + " took: " + fmt.Sprint(now.Sub(mark))
}
