package triggers

import (
	"encoding/json"
	"fmt"
)

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See NOTICE.txt in the project root for license information.

var _ Trigger = BlobTrigger{}

type BlobTrigger struct {
	Pipelines      *[]TriggerPipelineReference `json:"pipelines,omitempty"`
	TypeProperties BlobTriggerTypeProperties   `json:"typeProperties"`

	// Fields inherited from Trigger

	Annotations  *[]interface{}       `json:"annotations,omitempty"`
	Description  *string              `json:"description,omitempty"`
	RuntimeState *TriggerRuntimeState `json:"runtimeState,omitempty"`
	Type         string               `json:"type"`
}

func (s BlobTrigger) Trigger() BaseTriggerImpl {
	return BaseTriggerImpl{
		Annotations:  s.Annotations,
		Description:  s.Description,
		RuntimeState: s.RuntimeState,
		Type:         s.Type,
	}
}

var _ json.Marshaler = BlobTrigger{}

func (s BlobTrigger) MarshalJSON() ([]byte, error) {
	type wrapper BlobTrigger
	wrapped := wrapper(s)
	encoded, err := json.Marshal(wrapped)
	if err != nil {
		return nil, fmt.Errorf("marshaling BlobTrigger: %+v", err)
	}

	var decoded map[string]interface{}
	if err = json.Unmarshal(encoded, &decoded); err != nil {
		return nil, fmt.Errorf("unmarshaling BlobTrigger: %+v", err)
	}

	decoded["type"] = "BlobTrigger"

	encoded, err = json.Marshal(decoded)
	if err != nil {
		return nil, fmt.Errorf("re-marshaling BlobTrigger: %+v", err)
	}

	return encoded, nil
}
