package main

import (
	"fmt"
)

// Configuration holds the plugin settings from the Admin Console.
type Configuration struct {
	SharedSecret      string `json:"SharedSecret"`
	MaxActiveSessions int    `json:"MaxActiveSessions"`
	MaxStatusLines    int    `json:"MaxStatusLines"`
}

// Clone returns a shallow copy of the configuration.
func (c *Configuration) Clone() *Configuration {
	var clone Configuration
	clone = *c
	return &clone
}

// IsValid checks if the configuration is valid.
func (c *Configuration) IsValid() error {
	if c.SharedSecret == "" {
		return fmt.Errorf("SharedSecret must not be empty")
	}
	if c.MaxActiveSessions <= 0 {
		c.MaxActiveSessions = 20
	}
	if c.MaxStatusLines <= 0 {
		c.MaxStatusLines = 30
	}
	return nil
}

// getConfiguration retrieves the active configuration under lock.
func (p *Plugin) getConfiguration() *Configuration {
	p.configurationLock.RLock()
	defer p.configurationLock.RUnlock()

	if p.configuration == nil {
		return &Configuration{
			MaxActiveSessions: 20,
			MaxStatusLines:    30,
		}
	}

	return p.configuration
}

// OnConfigurationChange is invoked when configuration changes may have been made.
func (p *Plugin) OnConfigurationChange() error {
	var configuration = new(Configuration)

	if err := p.API.LoadPluginConfiguration(configuration); err != nil {
		return fmt.Errorf("failed to load plugin configuration: %w", err)
	}

	// Apply defaults
	if configuration.MaxActiveSessions <= 0 {
		configuration.MaxActiveSessions = 20
	}
	if configuration.MaxStatusLines <= 0 {
		configuration.MaxStatusLines = 30
	}

	p.configurationLock.Lock()
	p.configuration = configuration
	p.configurationLock.Unlock()

	return nil
}
