package usersubscribe

import (
	"context"
	"fmt"
	"go-admin/app/admin/models"
	"go-admin/common/database"
	"go-admin/common/global"
	"go-admin/common/helper"
	"go-admin/common/storage"
	"go-admin/config/serverinit"
	"go-admin/pkg/utility"
	"go-admin/services/fileservice"
	"log"
	"os"
	"os/signal"
	"strconv"
	"time"

	ext "go-admin/config"

	"github.com/go-admin-team/go-admin-core/config/source/file"
	"github.com/go-admin-team/go-admin-core/sdk"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	"github.com/go-admin-team/go-admin-core/sdk/pkg"
	"github.com/spf13/cobra"
	"gorm.io/gorm"
)

var (
	configYml string
	StartCmd  = &cobra.Command{
		Use:          "usersubscribe",
		Short:        "Start usersubscribe server",
		Example:      "go-admin usersubscribe -c config/settings.yml",
		SilenceUsage: true,
		PreRun: func(cmd *cobra.Command, args []string) {
			setup()
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			return run()
		},
	}
)

func init() {
	StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
}

func setup() {
	// 注入配置扩展项
	config.ExtendConfig = &ext.ExtConfig
	//1. 读取配置
	config.Setup(
		file.NewSource(file.WithPath(configYml)),
		database.Setup,
		storage.Setup,
	)
	//注册监听函数
	queue := sdk.Runtime.GetMemoryQueue("")
	queue.Register(global.LoginLog, models.SaveLoginLog)
	queue.Register(global.OperateLog, models.SaveOperaLog)
	// queue.Register(global.ApiCheck, models.SaveSysApi)
	go queue.Run()

	usageStr := `starting user subscribe server...`
	log.Println(usageStr)
}

func run() error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	var db *gorm.DB
	dbs := sdk.Runtime.GetDb()

	for _, item := range dbs {
		db = item
		break
	}

	defaultInit(db, ctx)

	utility.SafeGo(func() {
		// 启动定时任务
		clearLogJob(db, ctx)
	})

	//自动重启websocket
	utility.SafeGo(func() {
		reconnect(ctx)
	})
	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit

	fmt.Printf("%s Shutdown Server ... \r\n", pkg.GetCurrentTimeStr())

	// if err := srv.Shutdown(ctx); err != nil {
	// 	log.Fatal("Server Shutdown:", err)
	// }
	log.Println("Server exiting")

	return nil
}

func defaultInit(db *gorm.DB, ctx context.Context) {

	//初始化 默认redis
	helper.InitDefaultRedis(ext.ExtConfig.Redis.Addr, ext.ExtConfig.Redis.Password, ext.ExtConfig.Redis.Db)
	helper.InitLockRedisConn(ext.ExtConfig.Redis.Addr, ext.ExtConfig.Redis.Password, strconv.Itoa(ext.ExtConfig.Redis.Db))

	err := helper.DefaultRedis.Ping()

	if err != nil {
		log.Printf("初始化redis失败!请检查配置")
		_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		cancel()
	} else {
		log.Printf("redis初始化成功")
	}

	//初始化连接
	serverinit.UserSubscribeInit(db, ctx)
}

// 定时清理日志
func clearLogJob(db *gorm.DB, ctx context.Context) {
	ticker := time.NewTicker(time.Hour * 1)
	defer ticker.Stop()

	select {
	case <-ctx.Done():
		return
	case <-ticker.C:
		fileservice.ClearLogs(db)
	}
}

// 定时重连websocket
func reconnect(ctx context.Context) error {
	ticker := time.NewTicker(time.Hour * 1)
	defer ticker.Stop()

	select {
	case <-ctx.Done():
		return nil
	case <-ticker.C:
		serverinit.RestartConnect()
	}

	return nil
}
