/*
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 (
	"sync"

	"github.com/cgrates/birpc/context"

	"github.com/cgrates/cgrates/config"
	"github.com/cgrates/cgrates/engine"
	"github.com/cgrates/cgrates/rankings"
	"github.com/cgrates/cgrates/servmanager"
	"github.com/cgrates/cgrates/utils"
)

// NewRankingService returns the RankingS Service
func NewRankingService(cfg *config.CGRConfig) *RankingService {
	return &RankingService{
		cfg:       cfg,
		stateDeps: NewStateDependencies([]string{utils.StateServiceUP, utils.StateServiceDOWN}),
	}
}

type RankingService struct {
	mu        sync.RWMutex
	cfg       *config.CGRConfig
	ran       *rankings.RankingS
	stateDeps *StateDependencies // channel subscriptions for state changes
}

// Start should handle the sercive start
func (ran *RankingService) Start(shutdown *utils.SyncedChan, registry *servmanager.ServiceRegistry) (err error) {
	srvDeps, err := WaitForServicesToReachState(utils.StateServiceUP,
		[]string{
			utils.CommonListenerS,
			utils.ConnManager,
			utils.CacheS,
			utils.FilterS,
			utils.DB,
		},
		registry, ran.cfg.GeneralCfg().ConnectTimeout)
	if err != nil {
		return err
	}
	cl := srvDeps[utils.CommonListenerS].(*CommonListenerService).CLS()
	cms := srvDeps[utils.ConnManager].(*ConnManagerService)
	cacheS := srvDeps[utils.CacheS].(*CacheService)
	if err = cacheS.WaitToPrecache(shutdown,
		utils.CacheRankingProfiles,
		utils.CacheRankings); err != nil {
		return err
	}
	fs := srvDeps[utils.FilterS].(*FilterService)
	dbs := srvDeps[utils.DB].(*DataDBService)

	ran.mu.Lock()
	defer ran.mu.Unlock()
	ran.ran = rankings.NewRankingS(dbs.DataManager(), cms.ConnManager(), fs.FilterS(), ran.cfg)
	if err := ran.ran.StartRankingS(context.TODO()); err != nil {
		return err
	}
	srv, err := engine.NewService(ran.ran)
	if err != nil {
		return err
	}
	for _, s := range srv {
		cl.RpcRegister(s)
	}
	cms.AddInternalConn(utils.RankingS, srv)
	return nil
}

// Reload handles the change of config
func (ran *RankingService) Reload(_ *utils.SyncedChan, _ *servmanager.ServiceRegistry) (err error) {
	ran.mu.Lock()
	ran.ran.Reload(context.TODO())
	ran.mu.Unlock()
	return
}

// Shutdown stops the service
func (ran *RankingService) Shutdown(registry *servmanager.ServiceRegistry) (err error) {
	ran.mu.Lock()
	defer ran.mu.Unlock()
	ran.ran.StopRankingS()
	ran.ran = nil
	cl := registry.Lookup(utils.CommonListenerS).(*CommonListenerService).CLS()
	cl.RpcUnregisterName(utils.RankingSv1)
	return
}

// ServiceName returns the service name
func (ran *RankingService) ServiceName() string {
	return utils.RankingS
}

// ShouldRun returns if the service should be running
func (ran *RankingService) ShouldRun() bool {
	return ran.cfg.RankingSCfg().Enabled
}

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