package commands

import (
	"fmt"

	"github.com/kardianos/service"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
)

var logger service.Logger

type program struct {
	ctx *cli.Context
}

func (p *program) Start(s service.Service) error {
	//go p.run()
	return nil
}

func (p *program) Stop(s service.Service) error {
	// Stop should not block. Return with a few seconds.
	return nil
}

// CmdService cli 命令
var CmdService = cli.Command{
	Name:        "service",
	Usage:       "./pbx-api-gin service",
	Description: "PBX API install/uninstall",
	Action:      runService,
	Flags: []cli.Flag{
		cli.StringFlag{Name: "action, a", Usage: "install/uninstall/start/stop"},
		cli.StringFlag{Name: "config, c", Usage: "配置文件路径"},
		cli.Int64Flag{Name: "port, p", Usage: "默认绑定端口 8080", Value: 8080},
		cli.StringFlag{Name: "host", Usage: "默认绑定地址 0.0.0.0", Value: "0.0.0.0"},
	},
}

func runService(ctx *cli.Context) {
	svcConfig := &service.Config{
		Name:        "PBX-API",
		DisplayName: "PBX-API",
		Description: "PBX-API as service.",
		Arguments:   []string{"--config", ctx.String("config")},
	}

	prg := &program{
		ctx: ctx,
	}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		logrus.Fatal(err)
	}
	logger, err = s.Logger(nil)
	if err != nil {
		logrus.Fatal(err)
	}

	switch ctx.String("action") {
	case "install":
		if !ctx.IsSet("config") {
			fmt.Print("install must set config path, please by  -config set")
			return
		}
		err = s.Install()
		if err != nil {
			fmt.Println("install err", err)
		} else {
			fmt.Println("install success")
		}
		return
	case "uninstall":
		err = s.Uninstall()
		if err != nil {
			fmt.Println("Uninstall err", err)
		} else {
			fmt.Println("Uninstall success")
		}
		return
	case "start":
		s.Start()
		return
	case "stop":
		s.Stop()
		return
	}

	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
