package discovery

import (
	//"bytes"
	"encoding/json"
	"encoding/xml"
	"git.loafle.net/overflow/overflow_probe/discovery/discovery/types"
	"git.loafle.net/overflow/overflow_probe/discovery/discovery/types/timestamp"
	"github.com/cihub/seelog"
	"io/ioutil"
	//"net/http"
	"os"
)

type Conf struct {
	Version  string `xml:"version,attr"`
	Url      string `xml:"url"`
	User     string `xml:"user"`
	Password string `xml:"password"`
	BodyType string `xml:"bodyType"`
}

func sendBridge(dhs []types.DiscoveryHistory) {

	fp, err := os.Open("bin/bridge_conf.xml")
	if err != nil {
		panic(err)
	}
	defer fp.Close()

	data, err := ioutil.ReadAll(fp)

	var conf Conf
	xmlerr := xml.Unmarshal(data, &conf)
	if xmlerr != nil {
		panic(xmlerr)
	}

	for _, dh := range dhs {

		dh.Result = true
		dh.EndDate = timestamp.Now()
		//map -> slice
		convertMapToSlice(dh.Zone)

		data, _ := json.Marshal(&dh)
		seelog.Debug("!!! " + string(data))

		//for _, z := range dh.Zone.Histories {
		//	seelog.Debug("Host History : Start ")
		//	hostH, _ := json.Marshal(&z)
		//	seelog.Debug("Host" + string(hostH))
		//	seelog.Debug("Host History : End ")
		//}
		//
		//for _, h := range dh.Zone.Hosts {
		//
		//	for _, hh := range h.Histories {
		//		portH, _ := json.Marshal(&hh)
		//		seelog.Debug("Port History Start ")
		//		//seelog.Debug("Port Number: " + hh.PortNumber)
		//		//seelog.Debug("Port Type: "+hh.PortType)
		//		seelog.Debug(string(portH))
		//		seelog.Debug("Port History End ")
		//	}
		//
		//	for _, p := range h.Ports {
		//		for _, sh := range p.Histories {
		//			seelog.Debug("Service History Start")
		//			serviceH, _ := json.Marshal(&sh)
		//			//seelog.Debug("Service Name : " + sh.ServiceName)
		//			seelog.Debug(string(serviceH))
		//			seelog.Debug("Service History End")
		//		}
		//
		//	}
		//}

		//resp, _ := http.Post(conf.Url, conf.BodyType, bytes.NewBuffer(data))
		//body, _ := ioutil.ReadAll(resp.Body)
		//seelog.Debug(resp.Status)
		//seelog.Debug(resp.StatusCode)
		//seelog.Debug(string(body))
		//resp.Body.Close()
	}

}

func convertMapToSlice(zone *types.DiscoveryZone) {

	for _, host := range zone.Hosts_ {
		zone.Hosts = append(zone.Hosts, host)

		for _, port := range host.Ports_ {
			host.Ports = append(host.Ports, port)

		}

	}

}
