package rules

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/url"
	"time"

	"github.com/google/uuid"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"iwarma.ru/console/correlator/config"
)

// DumpNetwork Dump network request/response for debug purpose
func DumpNetwork(action string, url url.URL, request map[string]interface{}, response []byte, status int) {
	data := make(map[string]interface{})

	data["url"] = url
	data["request"] = request
	data["response"] = string(response)
	data["status"] = status

	dumpData, err := json.MarshalIndent(data, "", "\t")
	if err != nil {
		log.Errorf("Can't dump request: %v", err)
		log.Debugf("Sending request: %v", request)
		log.Debugf("Got response: %v", string(response))
	}

	fileName := fmt.Sprintf("%v/correlator_debug-%v_%v_action_%v.json", viper.GetString(config.DebugDumpPath), uuid.New(), action, time.Now().Unix())

	err = ioutil.WriteFile(fileName, dumpData, 0644)
	if err != nil {
		log.Errorf("Can't dump request: %v", err)
		log.Debugf("Sending request: %v", request)
		log.Debugf("Got response: %v", string(response))
	}
}
