package main

import (
	"context"
	"fmt"
	"golang.source-fellows.com/pattern/adapter/internal"
	"golang.source-fellows.com/pattern/adapter/internal/http"
	"golang.source-fellows.com/pattern/adapter/internal/model"
	"golang.source-fellows.com/pattern/adapter/internal/sql"
	"log"
	stdhttp "net/http"
)

func main() {

	ctx := context.Background()

	go dummyServer()

	waitForServer()

	customer := model.Customer{}
	stores := []internal.ContractStore{
		sql.NewContractStore(),
		http.NewContractStore(),
	}
	contractList := internal.NewContractList(stores)

	contracts, err := contractList.GetAllContracts(ctx, customer)
	if err != nil {
		log.Fatal(err)
	}
	for _, contract := range contracts {
		fmt.Println(contract)
	}

}

func waitForServer() {
	for {
		response, err := stdhttp.Get("http://localhost:8080")
		if err != nil {
			continue
		}
		if response.StatusCode != stdhttp.StatusOK {
			continue
		}
		return
	}
}

func dummyServer() {
	fmt.Println("starting dummy")
	fmt.Println(stdhttp.ListenAndServe(":8080", stdhttp.HandlerFunc(func(res stdhttp.ResponseWriter, r *stdhttp.Request) {
		res.Header().Set("Content-Type", "application/json")
		res.Write([]byte("[{\"name\":\"JSON Contract\"}]"))
	})))
	fmt.Println("dummy ended")
}
