/*
Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments
Copyright (C) ITsysCOM GmbH

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>
*/

package services

import (
	"fmt"
	"sync"

	"github.com/cgrates/cgrates/agents"
	"github.com/cgrates/cgrates/config"
	"github.com/cgrates/cgrates/servmanager"
	"github.com/cgrates/cgrates/utils"
)

// NewRadiusAgent returns the Radius Agent
func NewRadiusAgent(cfg *config.CGRConfig) *RadiusAgent {
	return &RadiusAgent{
		cfg:       cfg,
		stateDeps: NewStateDependencies([]string{utils.StateServiceUP, utils.StateServiceDOWN}),
	}
}

// RadiusAgent implements Agent interface
type RadiusAgent struct {
	mu        sync.RWMutex
	cfg       *config.CGRConfig
	stopChan  chan struct{}
	rad       *agents.RadiusAgent
	stateDeps *StateDependencies // channel subscriptions for state changes
}

// Start should handle the sercive start
func (rad *RadiusAgent) Start(shutdown *utils.SyncedChan, registry *servmanager.ServiceRegistry) (err error) {
	srvDeps, err := WaitForServicesToReachState(utils.StateServiceUP,
		[]string{
			utils.ConnManager,
			utils.FilterS,
			utils.CapS,
		},
		registry, rad.cfg.GeneralCfg().ConnectTimeout)
	if err != nil {
		return
	}
	cms := srvDeps[utils.ConnManager].(*ConnManagerService).ConnManager()
	fs := srvDeps[utils.FilterS].(*FilterService).FilterS()
	caps := srvDeps[utils.CapS].(*CapService).Caps()

	rad.mu.Lock()
	defer rad.mu.Unlock()

	if rad.rad, err = agents.NewRadiusAgent(rad.cfg, fs, cms, caps); err != nil {
		return
	}
	rad.stopChan = make(chan struct{})

	go rad.listenAndServe(rad.rad, shutdown)
	return
}

func (rad *RadiusAgent) listenAndServe(r *agents.RadiusAgent, shutdown *utils.SyncedChan) (err error) {
	if err = r.ListenAndServe(rad.stopChan); err != nil {
		utils.Logger.Err(fmt.Sprintf("<%s> error: <%s>", utils.RadiusAgent, err.Error()))
		shutdown.CloseOnce()
	}
	return
}

// Reload handles the change of config
func (rad *RadiusAgent) Reload(shutdown *utils.SyncedChan, registry *servmanager.ServiceRegistry) (err error) {
	rad.Shutdown(registry)
	return rad.Start(shutdown, registry)
}

// Shutdown stops the service
func (rad *RadiusAgent) Shutdown(_ *servmanager.ServiceRegistry) error {
	if rad.rad == nil {
		return nil
	}
	close(rad.stopChan)
	rad.rad.Wait()
	rad.mu.Lock()
	defer rad.mu.Unlock()
	rad.rad = nil
	return nil
}

// ServiceName returns the service name
func (rad *RadiusAgent) ServiceName() string {
	return utils.RadiusAgent
}

// ShouldRun returns if the service should be running
func (rad *RadiusAgent) ShouldRun() bool {
	return rad.cfg.RadiusAgentCfg().Enabled
}

// StateChan returns signaling channel of specific state
func (rad *RadiusAgent) StateChan(stateID string) chan struct{} {
	return rad.stateDeps.StateChan(stateID)
}
