package rules

import (
	"errors"
	"iwarma.ru/console/correlator/events"
	"sync"
)

// TestAction is an Action for testing purpose
type TestAction struct {
	PerformError        bool
	ParseInterfaceError bool
	MarshalError        bool
	UnmarshalError      bool
}

var (
	performCount    int
	performMutex    sync.Mutex
	eventsProcessed int
)

func performCountUpdate() {
	performMutex.Lock()
	defer performMutex.Unlock()

	performCount++
}

func PerformCountClear() {
	performMutex.Lock()
	defer performMutex.Unlock()

	performCount = 0
}

func GetPerformCount() int {
	performMutex.Lock()
	defer performMutex.Unlock()

	return performCount
}

func EventsProcessedClear() {
	performMutex.Lock()
	defer performMutex.Unlock()

	eventsProcessed = 0
}

func GetEventsProcessed() int {
	performMutex.Lock()
	defer performMutex.Unlock()

	return eventsProcessed
}

func (action TestAction) GetType() string {
	return "TEST"
}

func (action TestAction) Perform(events *[]*events.Event) error {
	performCountUpdate()

	performMutex.Lock()
	defer performMutex.Unlock()
	eventsProcessed += len(*events)

	if action.PerformError {
		return errors.New("test error")
	} else {
		return nil
	}
}

func (action *TestAction) ParseInterface(v interface{}) error {
	if action.ParseInterfaceError {
		return errors.New("test error")
	} else {
		return nil
	}
}

func (action TestAction) MarshalJSON() ([]byte, error) {
	if action.MarshalError {
		return nil, errors.New("test error")
	} else {
		return []byte(`{"type":"test"}`), nil
	}
}

func (action *TestAction) UnmarshalJSON(b []byte) error {
	if action.UnmarshalError {
		return errors.New("test error")
	} else {
		return nil
	}
}
