package comm

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/nats-io/nats.go"
)

// 客户端运行
var _currAppId = ""

func LancherClientRun(bus *NatsBus, ExePath string, configfile string, iconUrl string) error {
	currApp, e := ParseConfigFile(configfile)
	if e != nil {
		return e
	}

	id := GetAppPathId(ExePath)
	_currAppId = id

	currApp.Id = id
	currApp.LastRuningTime = time.Now()
	currApp.RegTime = time.Now()
	currApp.Status = APPSTATE_RUNNING
	currApp.IconUrl = iconUrl

	pwd, err := os.Getwd()
	if err != nil {
		return err
	}
	currApp.Pwd = pwd

	currApp.ExeFpath = ExePath
	currApp.Args = strings.Join(os.Args[1:], " ")
	nc := bus.GetNatsConn()
	js, e := nc.JetStream()
	if e != nil {
		return e
	}

	payload, e := json.Marshal(currApp)
	if e != nil {
		return e
	}

	kv, e := js.CreateKeyValue(&nats.KeyValueConfig{Bucket: "lancher-apps"})
	if e != nil {
		return e
	}
	v, e := kv.Get(currApp.Id)
	if e != nil {
		if e == nats.ErrKeyNotFound {
			_, e := kv.Put(currApp.Id, payload)
			if e != nil {
				return e
			}
			return nil

		} else {
			return nil
		}
	}
	lastApp := &App{}
	e = json.Unmarshal(v.Value(), lastApp)
	if e != nil {
		return e
	}
	lastApp.Name = currApp.Name
	lastApp.Label = currApp.Label
	lastApp.Icon = currApp.Icon
	lastApp.Desc = currApp.Name
	lastApp.LastRuningTime = time.Now()
	lastApp.Status = currApp.Status
	lastApp.IconUrl = currApp.IconUrl
	lastApp.ExeFpath = currApp.ExeFpath
	lastApp.Args = currApp.Args
	lastApp.Pwd = currApp.Pwd

	payload, _ = json.Marshal(lastApp)
	_, e = kv.Update(currApp.Id, payload, v.Revision())
	if e != nil {
		return e
	}
	kv.Purge(currApp.Id, nats.LastRevision(v.Revision()))
	vs, _ := kv.History(currApp.Id)
	fmt.Println(len(vs))

	return nil
}

func LancherClientQuitApp(bus *NatsBus) {
	nc := bus.GetNatsConn()
	js, e := nc.JetStream()
	if e != nil {
		return
	}
	kv, e := js.CreateKeyValue(&nats.KeyValueConfig{Bucket: "lancher-apps"})
	if e != nil {
		return
	}
	v, e := kv.Get(_currAppId)
	if e != nil {
		return
	}

	lastApp := &App{}
	e = json.Unmarshal(v.Value(), lastApp)
	if e != nil {
		return
	}
	lastApp.Status = APPSTATE_INSTALLED
	payload, _ := json.Marshal(lastApp)
	kv.Update(_currAppId, payload, v.Revision())
}
