package rpc

import (
	"fmt"
	"time"

	"git.loafle.net/commons_go/logging"

	cc "git.loafle.net/commons_go/config"
	ooccn "git.loafle.net/overflow/overflow_commons_go/config/noauthprobe"
	oocmn "git.loafle.net/overflow/overflow_commons_go/modules/noauthprobe"
	oopai "git.loafle.net/overflow/overflow_probes/auth/info"
	"git.loafle.net/overflow/overflow_probes/config"
)

type NoAuthProbeService struct {
	DoneChan chan error

	ConfigPath string
	Config     ooccn.NoAuthProbeConfig
}

func (s *NoAuthProbeService) Accept(probeKey string) error {
	config.Config.Probe.Key = &probeKey

	if err := cc.Save(*config.Config, *config.ConfigFilePath, true); nil != err {
		s.DoneChan <- fmt.Errorf("Auth: Saving of config file[%s] failed error[%v]", *config.ConfigFilePath, err)
		return nil
	}

	logging.Logger().Infof("Auth: Probe[%s] has been accepted from central", probeKey)
	s.DoneChan <- nil

	return nil
}

func (s *NoAuthProbeService) Deny() error {
	n := time.Now()
	s.Config.DenyDate = &n
	if err := cc.Save(s.Config, s.ConfigPath, true); nil != err {
		s.DoneChan <- fmt.Errorf("Auth: Saving of NoAuth config file[%s] failed error[%v]", s.ConfigPath, err)
		return nil
	}

	logging.Logger().Infof("Auth: Probe has been denyed from central")
	s.DoneChan <- nil
	return nil
}

func (s *NoAuthProbeService) GetRequestHeader() map[string][]string {
	header := make(map[string][]string)
	switch s.Config.State() {
	case ooccn.NoAuthProbeStateTypeNotRegisterd:
		header[oocmn.HTTPRequestHeaderKey_NoAuthProbe_Method] = []string{oocmn.HTTPRequestHeaderValue_NoAuthProbe_Method_Regist}
		header[oocmn.HTTPRequestHeaderKey_NoAuthProbe_Info] = []string{s.GetRegisterRequestHeader()}

	case ooccn.NoAuthProbeStateTypeRegisterd:
		header[oocmn.HTTPRequestHeaderKey_NoAuthProbe_Method] = []string{oocmn.HTTPRequestHeaderValue_NoAuthProbe_Method_Connect}
		header[oocmn.HTTPRequestHeaderKey_NoAuthProbe_TempProbeKey] = []string{*s.Config.TempKey}
	}

	return header
}

func (s *NoAuthProbeService) GetRegisterRequestHeader() string {
	i, err := oopai.GetRegistHeader()
	if nil != err {
		logging.Logger().Errorf("Auth: Gathering system information has been failed %v", err)
	}
	return i
}

func (s *NoAuthProbeService) SetTempProbeKey(tempProbeKey string) {
	s.Config.TempKey = &tempProbeKey
	if err := cc.Save(s.Config, s.ConfigPath, true); nil != err {
		s.DoneChan <- fmt.Errorf("Auth: Saving of NoAuth config file[%s] failed error[%v]", s.ConfigPath, err)
		return
	}

}
