/*
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 config

import (
	"slices"
	"time"

	"github.com/cgrates/birpc/context"
	"github.com/cgrates/cgrates/utils"
)

// KamConnCfg represents one connection instance towards Kamailio
type KamConnCfg struct {
	Alias                string
	Address              string
	Reconnects           int
	MaxReconnectInterval time.Duration
}

func (kamCfg *KamConnCfg) loadFromJSONCfg(jsnCfg *KamConnJsonCfg) (err error) {
	if jsnCfg == nil {
		return
	}
	if jsnCfg.Address != nil {
		kamCfg.Address = *jsnCfg.Address
	}
	if jsnCfg.Alias != nil {
		kamCfg.Alias = *jsnCfg.Alias
	}
	if jsnCfg.Reconnects != nil {
		kamCfg.Reconnects = *jsnCfg.Reconnects
	}
	if jsnCfg.Max_reconnect_interval != nil {
		if kamCfg.MaxReconnectInterval, err = utils.ParseDurationWithNanosecs(*jsnCfg.Max_reconnect_interval); err != nil {
			return
		}
	}
	return
}

// AsMapInterface returns the config as a map[string]any
func (kamCfg KamConnCfg) AsMapInterface() map[string]any {
	return map[string]any{
		utils.AliasCfg:                kamCfg.Alias,
		utils.AddressCfg:              kamCfg.Address,
		utils.ReconnectsCfg:           kamCfg.Reconnects,
		utils.MaxReconnectIntervalCfg: kamCfg.MaxReconnectInterval.String(),
	}
}

// Clone returns a deep copy of KamConnCfg
func (kamCfg KamConnCfg) Clone() *KamConnCfg {
	return &KamConnCfg{
		Alias:                kamCfg.Alias,
		Address:              kamCfg.Address,
		Reconnects:           kamCfg.Reconnects,
		MaxReconnectInterval: kamCfg.MaxReconnectInterval,
	}
}

// KamAgentCfg is the Kamailio config section
type KamAgentCfg struct {
	Enabled       bool
	SessionSConns []string
	CreateCdr     bool
	EvapiConns    []*KamConnCfg
	Timezone      string
}

// loadKamAgentCfg loads the KamAgent section of the configuration
func (ka *KamAgentCfg) Load(ctx *context.Context, jsnCfg ConfigDB, _ *CGRConfig) (err error) {
	jsnKamAgentCfg := new(KamAgentJsonCfg)
	if err = jsnCfg.GetSection(ctx, KamailioAgentJSON, jsnKamAgentCfg); err != nil {
		return
	}
	return ka.loadFromJSONCfg(jsnKamAgentCfg)
}

func (ka *KamAgentCfg) loadFromJSONCfg(jsnCfg *KamAgentJsonCfg) error {
	if jsnCfg == nil {
		return nil
	}
	if jsnCfg.Enabled != nil {
		ka.Enabled = *jsnCfg.Enabled
	}
	if jsnCfg.Sessions_conns != nil {
		ka.SessionSConns = tagInternalConns(*jsnCfg.Sessions_conns, utils.MetaSessionS)
	}
	if jsnCfg.Create_cdr != nil {
		ka.CreateCdr = *jsnCfg.Create_cdr
	}
	if jsnCfg.Evapi_conns != nil {
		ka.EvapiConns = make([]*KamConnCfg, len(*jsnCfg.Evapi_conns))
		for idx, jsnConnCfg := range *jsnCfg.Evapi_conns {
			ka.EvapiConns[idx] = getDftKamConnCfg()
			ka.EvapiConns[idx].loadFromJSONCfg(jsnConnCfg)
		}
	}
	if jsnCfg.Timezone != nil {
		ka.Timezone = *jsnCfg.Timezone
	}
	return nil
}

// AsMapInterface returns the config as a map[string]any
func (ka KamAgentCfg) AsMapInterface() any {
	mp := map[string]any{
		utils.EnabledCfg:   ka.Enabled,
		utils.CreateCdrCfg: ka.CreateCdr,
		utils.TimezoneCfg:  ka.Timezone,
	}
	if ka.EvapiConns != nil {
		evapiConns := make([]map[string]any, len(ka.EvapiConns))
		for i, item := range ka.EvapiConns {
			evapiConns[i] = item.AsMapInterface()
		}
		mp[utils.EvapiConnsCfg] = evapiConns
	}
	if ka.SessionSConns != nil {
		mp[utils.SessionSConnsCfg] = stripInternalConns(ka.SessionSConns)
	}
	return mp
}

func (KamAgentCfg) SName() string            { return KamailioAgentJSON }
func (ka KamAgentCfg) CloneSection() Section { return ka.Clone() }

// Clone returns a deep copy of KamAgentCfg
func (ka KamAgentCfg) Clone() (cln *KamAgentCfg) {
	cln = &KamAgentCfg{
		Enabled:   ka.Enabled,
		CreateCdr: ka.CreateCdr,
		Timezone:  ka.Timezone,
	}
	if ka.SessionSConns != nil {
		cln.SessionSConns = slices.Clone(ka.SessionSConns)
	}
	if ka.EvapiConns != nil {
		cln.EvapiConns = make([]*KamConnCfg, len(ka.EvapiConns))
		for i, req := range ka.EvapiConns {
			cln.EvapiConns[i] = req.Clone()
		}
	}
	return
}

// Represents one connection instance towards Kamailio
type KamConnJsonCfg struct {
	Alias                  *string
	Address                *string
	Reconnects             *int
	Max_reconnect_interval *string
}

func diffKamConnJsonCfg(v1, v2 *KamConnCfg) (d *KamConnJsonCfg) {
	d = new(KamConnJsonCfg)
	if v1.Alias != v2.Alias {
		d.Alias = utils.StringPointer(v2.Alias)
	}
	if v1.Address != v2.Address {
		d.Address = utils.StringPointer(v2.Address)
	}
	if v1.Reconnects != v2.Reconnects {
		d.Reconnects = utils.IntPointer(v2.Reconnects)
	}
	if v1.MaxReconnectInterval != v2.MaxReconnectInterval {
		d.Max_reconnect_interval = utils.StringPointer(v2.MaxReconnectInterval.String())
	}
	return
}

// KamAgentJsonCfg kamailio config section
type KamAgentJsonCfg struct {
	Enabled        *bool
	Sessions_conns *[]string
	Create_cdr     *bool
	Evapi_conns    *[]*KamConnJsonCfg
	Timezone       *string
}

func equalsKamConnsCfg(v1, v2 []*KamConnCfg) bool {
	if len(v1) != len(v2) {
		return false
	}
	for i := range v2 {
		if v1[i].Alias != v2[i].Alias ||
			v1[i].Address != v2[i].Address ||
			v1[i].Reconnects != v2[i].Reconnects ||
			v1[i].MaxReconnectInterval != v2[i].MaxReconnectInterval {
			return false
		}
	}
	return true
}

func diffKamAgentJsonCfg(d *KamAgentJsonCfg, v1, v2 *KamAgentCfg) *KamAgentJsonCfg {
	if d == nil {
		d = new(KamAgentJsonCfg)
	}
	if v1.Enabled != v2.Enabled {
		d.Enabled = utils.BoolPointer(v2.Enabled)
	}
	if !slices.Equal(v1.SessionSConns, v2.SessionSConns) {
		d.Sessions_conns = utils.SliceStringPointer(stripInternalConns(v2.SessionSConns))
	}
	if v1.CreateCdr != v2.CreateCdr {
		d.Create_cdr = utils.BoolPointer(v2.CreateCdr)
	}
	if !equalsKamConnsCfg(v1.EvapiConns, v2.EvapiConns) {
		dft := getDftKamConnCfg()
		conns := make([]*KamConnJsonCfg, len(v2.EvapiConns))
		for i, conn := range v2.EvapiConns {
			conns[i] = diffKamConnJsonCfg(dft, conn)
		}
		d.Evapi_conns = &conns
	}
	if v1.Timezone != v2.Timezone {
		d.Timezone = utils.StringPointer(v2.Timezone)
	}
	return d
}
