package common

import (
	"fmt"

	"github.com/fiskerinc/cloud-services/pkg/common/dbbasemodel"
	"github.com/google/uuid"
)

type SubscriptionFeature struct {
	ID             uuid.UUID                   `json:"id" pg:"type:uuid,default:uuid_generate_v4()"`
	Name           string                      `json:"name" validate:"required,max=256"`
	Description    string                      `json:"description" validate:"required,max=5120"`
	Configurations []SubscriptionConfiguration `json:"configurations,omitempty" pg:"rel:has-many"`
	dbbasemodel.DBModelBase
}

func (sf *SubscriptionFeature) HasConfig(config *SubscriptionConfiguration) bool {
	for _, item := range sf.Configurations {
		if item.ECU == config.ECU {
			return true
		}
	}

	return false
}

func (sf *SubscriptionFeature) AddConfig(config *SubscriptionConfiguration) {
	if !sf.HasConfig(config) {
		sf.Configurations = append(sf.Configurations, *config)
	}
}

func (sf *SubscriptionFeature) RemoveConfig(config *SubscriptionConfiguration) {
	if sf.HasConfig(config) {
		configs := make([]SubscriptionConfiguration, len(sf.Configurations)-1)
		for _, item := range sf.Configurations {
			if config.SubscriptionFeatureID != item.SubscriptionFeatureID && config.ECU != item.ECU {
				configs[len(configs)] = item
			}
		}
	}
}

func (sf *SubscriptionFeature) String() string {
	return fmt.Sprintf("SubscriptionFeature<%v>", sf.ID)
}
