package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
)

/*
Permet d'obetenir le token et le user_id à partir du nom et du password ecoledirecte
*/
func get_login_token(id string, psw string) (user_id string, x_token string) {

	url := "https://api.ecoledirecte.com/v3/login.awp?v=4.65.0"
	fmt.Println("URL:>", url)

	var jsonStr = []byte(`data={
    "identifiant": "` + id + `",
    "motdepasse": "` + psw + `",
    "isReLogin": false,
    "cn": "ED_UExVTUVfMDY3MTYwOUtfMV8zMTIw",
    "cv": "NGE3OTU0NDc0ZTc5NzQ1NjUxNjU1MDc2NDU1YTc4NTQ3NTcyNmM0MzM1NGUzMTM3NjY1MTU4MzE=",
    "uuid": "",
    "fa": [
        {
            "cn": "ED_UExVTUVfMDY3MTYwOUtfMV8zMTIw",
            "cv": "NGE3OTU0NDc0ZTc5NzQ1NjUxNjU1MDc2NDU1YTc4NTQ3NTcyNmM0MzM1NGUzMTM3NjY1MTU4MzE="
        }
    ]
}`)
	fmt.Println("REQUEST DATA:\n", string(jsonStr), "\n\n\n")
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	//req.Header.Set("X-Custom-Header", "myvalue")
	req.Header.Set("Content-Length", string(len(jsonStr)))
	req.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd")
	req.Header.Set("Accept", "application/json, text/plain, */*")
	req.Header.Set("Accept-Language", "en-US,en;q=0.5")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Host", "api.ecoledirecte.com")
	req.Header.Set("Origin", "https://www.ecoledirecte.com")
	req.Header.Set("Referer", "https://www.ecoledirecte.com/")
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Sec-Fetch-Mode", "cors")
	req.Header.Set("Sec-Fetch-Site", "same-site")
	req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0")
	//req.Header.Set("X-Token", "2d4db09a-d27f-400c-9851-9602d2878183")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("response Status:", resp.Status)
	fmt.Println("response Headers:", resp.Header)
	body, _ := io.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))

	// C'est un peu hacky mais ça permet d'avoir l'id de l'utilisateur, exemple 3605
	body_str := string(body)
	index := strings.Index(body_str, `"eleves":[{"id":`)
	userid := ""
	for i := 0; i < 8; i++ {
		char := fmt.Sprintf("%c", []rune(body_str)[index+13+i])
		if char != "," {
			userid = userid + char
		} else {
			break
		}
	}

	return userid, resp.Header.Get("X-Token")
}

type Data struct {
	Url string
}

type Url_Response struct {
	Code  int
	Token string
	Host  string
	Data  Data
}

/*
Retourne le lien de téléchargement de l'agenda ics à partir du token et du user_id
*/
func get_agenda_link(user_id string, x_token string) string {
	url := "https://api.ecoledirecte.com/v3/ical/E/" + user_id + "/url.awp?verbe=get&v=4.65.0"
	fmt.Println("URL:>", url)

	var jsonStr = []byte(`data={}`)

	fmt.Print("REQUEST DATA:\n", string(jsonStr), "\n\n\n")
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	//req.Header.Set("X-Custom-Header", "myvalue")
	req.Header.Set("Content-Length", "7")
	req.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd")
	req.Header.Set("Accept", "application/json, text/plain, */*")
	req.Header.Set("Accept-Language", "en-US,en;q=0.5")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Host", "api.ecoledirecte.com")
	req.Header.Set("Origin", "https://www.ecoledirecte.com")
	req.Header.Set("Referer", "https://www.ecoledirecte.com/")
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Sec-Fetch-Mode", "cors")
	req.Header.Set("Sec-Fetch-Site", "same-site")
	req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:131.0) Gecko/20100101 Firefox/131.0")
	req.Header.Set("X-Token", x_token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("response Status:", resp.Status)
	fmt.Println("response Headers:", resp.Header)
	body, _ := io.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))

	var jsonMap Url_Response
	json.Unmarshal(body, &jsonMap)
	response_url := jsonMap.Data.Url

	return "https://api.ecoledirecte.com/v3/" + response_url
}
