package rules

import (
	"encoding/json"
	"fmt"
	"testing"
)

func TestActionHttpMarshal(t *testing.T) {
	action := HttpAction{Url: "http://localhost:543/http", ContentType: "application/json", Template: `{{.event_id}}`}

	bytes, err := json.Marshal(action)
	if err != nil {
		t.Error(err)
	}

	if string(bytes) != `{"type":"http","url":"http://localhost:543/http","template":"{{.event_id}}","content_type":"application/json"}` {
		t.Error(fmt.Sprintf("Got result: %v", string(bytes)))
	}
}

func TestActionHttpUnmarshalGood(t *testing.T) {
	str := `{"type":"http","url":"http://localhost:543/http","template":"{{.event_id}}"}`

	var action HttpAction

	err := json.Unmarshal([]byte(str), &action)
	if err != nil {
		t.Error(err)
	}

	if action.Url != "http://localhost:543/http" {
		t.Error(fmt.Sprintf("Bad url, got %s", action.Url))
	}

	if action.Template != "{{.event_id}}" {
		t.Error(fmt.Sprintf("Got bad template: \"%s\"", action.Template))
	}
}

func TestActionHttpUnmarshalBad(t *testing.T) {
	str := `{"type":"syslog","url":"http://localhost:543/http","template":"{{.event_id}}"}`

	var action HttpAction

	err := json.Unmarshal([]byte(str), &action)
	if err == nil {
		t.Error("Don't get error with bad action type")
	}
}

func TestActionHttpParseInterfaceBad(t *testing.T) {
	data := make([]interface{}, 1)
	data[0] = 10

	action := new(HttpAction)

	err := action.ParseInterface(data)

	if err == nil {
		t.Error("No error with bad interfce")
	}
}

func TestActionHttpUnmarshalBad2(t *testing.T) {
	data := `Some strange test`

	action := new(HttpAction)

	err := action.UnmarshalJSON([]byte(data))
	if err == nil {
		t.Error("No error with bad json")
	}
}

func TestActionHttpParseInterfaceBad2(t *testing.T) {
	data := make(map[string]interface{})
	data["url"] = "http"

	action := new(HttpAction)

	err := action.ParseInterface(data)

	if err == nil {
		t.Error("No error with bad interfce")
	}
}
