package auth

import (
	"fmt"
	"time"

	lfcc "git.loafle.net/commons_go/config"
	"git.loafle.net/commons_go/logging"
	"git.loafle.net/overflow/overflow_probes/central/api/module"
)

func (h *authHandlers) onNotify(method string, params []string) {
	switch method {
	case module.NoAuthProbeService_AcceptNoAuthProbe:
		h.onNoAuthProbeAccept(params)
		break
	case module.NoAuthProbeService_DenyNoauthProbe:
		h.onNoAuthProbeDeny(params)
		break
	}

}

func (h *authHandlers) onNoAuthProbeAccept(params []string) {
	var err error
	probeID := params[0]

	if lfcc.Exists(h.probeConfigPath) {
		if err = lfcc.Load(&h.probeConfig, h.probeConfigPath); nil != err {
			logging.Logger.Error(fmt.Sprintf("Auth: Loading of Probe config file[%s] failed error[%v]", h.probeConfigPath, err))
		}
	}

	h.probeConfig.ID = &probeID
	if err = lfcc.Save(h.probeConfig, h.probeConfigPath, true); nil != err {
		logging.Logger.Error(fmt.Sprintf("Auth: Saving of Probe config file[%s] failed error[%v]", h.probeConfigPath, err))
	}

	h.acceptedChan <- true
}

func (h *authHandlers) onNoAuthProbeDeny(params []string) {
	n := time.Now()
	h.noAuthConfig.DenyDate = &n
	if err := lfcc.Save(h.noAuthConfig, h.noAuthConfigPath, true); nil != err {
		logging.Logger.Error(fmt.Sprintf("Auth: Saving of NoAuth config file[%s] failed error[%v]", h.noAuthConfigPath, err))
	}

	h.deniedChan <- fmt.Errorf("This probe have been denied from overFlow")
}
