package main

import (
	"flag"
	"fmt"

	"sundynix-micro-go/app/plant/rpc/internal/config"
	"sundynix-micro-go/app/plant/rpc/internal/server"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/internal/task"
	"sundynix-micro-go/app/plant/rpc/plant"
	"sundynix-micro-go/common/utils/timer"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/core/stat"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var configFile = flag.String("f", "etc/plant.yaml", "the config file")

func main() {
	flag.Parse()
	stat.DisableLog()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	// 注册定时任务
	timerTask := timer.NewTimerTask()
	// 每天凌晨 1:00 检查过期养护任务
	if _, err := timerTask.AddTaskByJob("plant", "0 1 * * *", task.NewExpireCareTaskJob(ctx), "expire_care_task"); err != nil {
		fmt.Printf("注册养护任务过期检查失败: %v\n", err)
	}

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		plant.RegisterPlantServiceServer(grpcServer, server.NewPlantServiceServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer func() {
		timerTask.Close()
		s.Stop()
	}()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
