package main

import (
	"fmt"
	"os"
	"os/signal"
)

// OnSignalCB callback type for signal
type OnSignalCB func(sig os.Signal)

// MonSignals .
type MonSignals struct {
	callback          map[string][]OnSignalCB
	registeredSignals []os.Signal
}

var monSig MonSignals

// MonitorSignals Routine used to monitor signals (eg. SIGINT, SIGTERM, ...)
func MonitorSignals() {

	monSig.callback = make(map[string][]OnSignalCB)
	monSig.registeredSignals = GetRegisteredSignals()

	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, monSig.registeredSignals...)

	go func() {
		for {
			sig := <-sigs
			Log.Debugf("Detect signal %v", sig)
			if cbArr, exist := monSig.callback[sig.String()]; exist {
				for _, cb := range cbArr {
					cb(sig)
				}
			}
		}
	}()
}

// isSupportSignal Check if a signal is supported or not
func isSupportSignal(sig os.Signal) bool {
	for _, s := range monSig.registeredSignals {
		if s == sig {
			return true
		}
	}
	return false
}

// OnSignal Register a callback for a specified signal
func OnSignal(sig os.Signal, fCB OnSignalCB) error {
	if !isSupportSignal(sig) {
		return fmt.Errorf("unsupported signal %v", sig)
	}
	sigStr := sig.String()
	monSig.callback[sigStr] = append(monSig.callback[sigStr], fCB)
	return nil
}

// OnSignals Register a callback for any signals
func OnSignals(fCB OnSignalCB) error {
	for _, s := range monSig.registeredSignals {
		if err := OnSignal(s, fCB); err != nil {
			return err
		}
	}
	return nil
}