package resources

import (
	"encoding/json"

	"cloud.o-forge.io/core/oc-lib/models/common/pricing"
	"cloud.o-forge.io/core/oc-lib/models/resources/native_tools"
	"cloud.o-forge.io/core/oc-lib/models/utils"
	"cloud.o-forge.io/core/oc-lib/tools"
)

/*
* NativeT ools is a struct that represents Native Functionnality of OPENCLOUD
 */
type NativeTool struct {
	AbstractResource
	Kind   int `json:"kind" bson:"kind" validate:"required"`
	Params map[string]interface{}
}

func (d *NativeTool) SetName(name string) {
	d.Name = name
}

func (d *NativeTool) GetAccessor(request *tools.APIRequest) utils.Accessor {
	return NewAccessor[*NativeTool](tools.NATIVE_TOOL, request)
}

func (r *NativeTool) AddInstances(instance ResourceInstanceITF) {
}

func (r *NativeTool) GetType() string {
	return tools.NATIVE_TOOL.String()
}

func (d *NativeTool) ClearEnv() utils.DBObject {
	return d
}

func (w *NativeTool) SetAllowedInstances(request *tools.APIRequest, ids ...string) []ResourceInstanceITF {
	// WorkflowResource has no instances, but still carries AEs that must be
	// filtered before the resource is returned to a non-owner, non-admin peer.
	if !((request != nil && request.PeerID == w.CreatorID && request.PeerID != "") || request.Admin) {
		if request != nil {
			w.FilterExploitationAuthorizations(request.PeerID, request.Admin)
		}
	}
	return []ResourceInstanceITF{}
}

func (w *NativeTool) ConvertToPricedResource(t tools.DataType, selectedInstance *int, selectedPartnership *int, selectedBuyingStrategy *int, selectedStrategy *int, selectedBookingModeIndex *int, request *tools.APIRequest) (pricing.PricedItemITF, error) {
	return &PricedResource[*pricing.ExploitPricingProfile[pricing.TimePricingStrategy]]{
		Name:         w.Name,
		Logo:         w.Logo,
		ResourceID:   w.UUID,
		ResourceType: t,
		Quantity:     1,
		CreatorID:    w.CreatorID,
	}, nil
}

func (r *NativeTool) GetSelectedInstance(selected *int) ResourceInstanceITF {
	return nil
}

func InitNative() {
	for _, kind := range []native_tools.NativeToolsEnum{native_tools.WORKFLOW_EVENT} {
		newNative := &NativeTool{}
		access := newNative.GetAccessor(&tools.APIRequest{Admin: true})
		l, _, err := access.Search(nil, kind.String(), false, 0, 10)
		if err != nil || len(l) == 0 {
			newNative.Name = kind.String()
			newNative.Kind = int(kind)
			b, _ := json.Marshal(kind.Params())
			var m map[string]interface{}
			json.Unmarshal(b, &m)
			newNative.Params = m
			access.StoreOne(newNative)
		}
	}
}
