package util

import (
	"context"
	"log"
	"os"
	"os/signal"
	"time"
)

type IShutdown interface {
	Shutdown(ctx context.Context) error
}

func GracefulShutdown(sd IShutdown, stopFn func()) {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit

	timeoutCtx, cancle := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancle()

	if sd != nil {
		err := sd.Shutdown(timeoutCtx)
		if err != nil {
			log.Println("ShutDown err: ", err)
		}
	}

	if stopFn != nil {
		stopFn()
	}
}
