package main

import (
	"flag"
	"fmt"
	"net/http"
	"io/ioutil"
	"strconv"
	"strings"
)

var (
	httpPort = flag.Int("http_port", 80, "HTTP port to serve on (defaults to 80)")
)

func main() {
	// Parse the flags
	flag.Parse()
	mux := http.NewServeMux()
	mux.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
		query := r.URL.Query()
		// host := strings.Split(query.Get("state"), "-")[1]
		clientId := query.Get("client_id")
		cozyOrigin := query.Get("redirect_uri") // here we use the redirect_uri param to transmit our stack url
		state := query.Get("state")
		response, err := http.Get("https://gw.hml.api.enedis.fr/group/espace-particuliers/consentement-linky/oauth2/authorize?client_id="+ clientId +"&duration=P6M&redirect_uri=https://oauth-proxy.wf.alpha.grandlyon.com/redirect&response_type=code&state="+ state +"-"+ cozyOrigin)
		if err != nil {
			fmt.Println(err)
		} else {
			defer response.Body.Close()
			contents, err := ioutil.ReadAll(response.Body)
			if err != nil {
				fmt.Println(err)
			}
			fmt.Printf("%s\n", string(contents))
		}
	
	})

	mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
		query := r.URL.Query()
		state := strings.Split(query.Get("state"), "-")[0]
		host := strings.Split(query.Get("state"), "-")[1]
		usagePointId := query.Get("usage_point_id")
		code := query.Get("code")
		redir := "https://" + host + "/accounts/enedisoauth/redirect?code=" + code + "&state="+ state +"&usage_point_id=" + usagePointId
		fmt.Println(redir)
		http.Redirect(w, r, redir, 302)
	})

	http.ListenAndServe(":"+strconv.Itoa(*httpPort), mux)
}