package main

import (
	"fmt"
	"log"
	"net/http"
	"sync/atomic"
	"time"
)

var processRunning = &atomic.Bool{}

var backgroundProcess = func() {
	log.Println("background process is now started")
	processRunning.Store(true)
	time.Sleep(4 * time.Second)
	processRunning.Store(false)
	log.Println("background process is now finished")
}

func start(response http.ResponseWriter, request *http.Request) {

	log.Println("call reached start")

	if !processRunning.Load() {
		go backgroundProcess()
		response.Header().Add("Location", buildLocation(request, "/status"))
		response.WriteHeader(http.StatusAccepted)
		return
	}

	response.WriteHeader(http.StatusNotAcceptable)
}

func status(response http.ResponseWriter, request *http.Request) {

	log.Println("call reached status")

	if processRunning.Load() {
		response.Header().Add("Retry-After", "1")
		response.Header().Add("Location", buildLocation(request, "/status"))
		response.WriteHeader(http.StatusOK)
		return
	}

	response.Header().Add("Location", buildLocation(request, "/result"))
	response.WriteHeader(http.StatusFound)

}

func result(response http.ResponseWriter, request *http.Request) {
	log.Println("call reached result")
	fmt.Fprintln(response, "Hello World!")
}

func buildLocation(request *http.Request, part string) string {
	return fmt.Sprintf("http://%s%s", request.Host, part)
}

func main() {

	http.HandleFunc("/start", start)
	http.HandleFunc("/status", status)
	http.HandleFunc("/result", result)

	log.Fatal(http.ListenAndServe(":8082", nil))

}
