"github.com/appc/cni/pkg/types"
	"github.com/cloudfoundry-incubator/ducati-daemon/client"
	"github.com/cloudfoundry-incubator/ducati-daemon/fakes"
	"github.com/cloudfoundry-incubator/ducati-daemon/models"
	"github.com/onsi/gomega/ghttp"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Client", func() {
	var (
		c           client.DaemonClient
		server      *ghttp.Server
		marshaler   *lfakes.Marshaler
		unmarshaler *lfakes.Unmarshaler

		roundTripper *fakes.RoundTripper
		httpClient   *http.Client
	)

	BeforeEach(func() {
		server = ghttp.NewServer()
		marshaler = &lfakes.Marshaler{}
		unmarshaler = &lfakes.Unmarshaler{}

		roundTripper = &fakes.RoundTripper{}
		roundTripper.RoundTripStub = http.DefaultTransport.RoundTrip

		httpClient = &http.Client{
			Transport: roundTripper,
	})

	AfterEach(func() {
		session.Interrupt()
		Eventually(session, DEFAULT_TIMEOUT).Should(gexec.Exit(0))
		Expect(containerRepo.Destroy(containerNamespace)).To(Succeed())
	})

	var serverIsAvailable = func() error {
		return VerifyTCPConnection(address)
	}

	Context("ducatid server restarts", func() {
		var (
			upSpec       models.CNIAddPayload
			downSpec     models.CNIDelPayload
			daemonClient *client.DaemonClient
			ipamResult   types.Result
		)

		BeforeEach(func() {
			Eventually(serverIsAvailable).Should(Succeed())

			daemonClient = client.New("http://"+address, http.DefaultClient)

			By("generating config and creating the request")
			upSpec = models.CNIAddPayload{
				Args:               "FOO=BAR;ABC=123",
				ContainerNamespace: containerNamespace.Name(),
				InterfaceName:      "vx-eth0",
				Network: models.NetworkPayload{
					models.Properties{
		return VerifyTCPConnection(address)
	}

	It("should boot and gracefully terminate", func() {
		Eventually(serverIsAvailable, DEFAULT_TIMEOUT).Should(Succeed())

		Consistently(session).ShouldNot(gexec.Exit())

		session.Interrupt()
		Eventually(session, DEFAULT_TIMEOUT).Should(gexec.Exit(0))
	})

	Describe("POST to /cni/add and /cni/del", func() {
		var (
			upSpec       models.CNIAddPayload
			downSpec     models.CNIDelPayload
			daemonClient *client.DaemonClient
			ipamResult   types.Result
		)

		BeforeEach(func() {
			Eventually(serverIsAvailable).Should(Succeed())

			daemonClient = client.New("http://"+address, http.DefaultClient)

			By("generating config and creating the request")
			upSpec = models.CNIAddPayload{
				Args:               "FOO=BAR;ABC=123",
				ContainerNamespace: containerNamespace.Name(),
				InterfaceName:      "vx-eth0",
				Network: models.NetworkPayload{
					models.Properties{