Skip to content
Snippets Groups Projects
voteragent.go 1.53 KiB
Newer Older
Balthazar Wilson's avatar
Balthazar Wilson committed
package voteragent
Balthazar Wilson's avatar
Balthazar Wilson committed
import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net/http"

	rad "gitlab.utc.fr/gvandevi/ia04binome2a"
	cs "gitlab.utc.fr/gvandevi/ia04binome2a/comsoc"
)

type RestClientAgent struct {
Balthazar Wilson's avatar
Balthazar Wilson committed
	id      string
	url     string
	scrutin string
	nbAlts  int
	prefs   []int
	options []int
Balthazar Wilson's avatar
Balthazar Wilson committed
func NewRestClientAgent(id string, url string, scrutin string, nbAlts int, prefs []int, options []int) *RestClientAgent {
	return &RestClientAgent{id, url, scrutin, nbAlts, prefs, options}
Balthazar Wilson's avatar
Balthazar Wilson committed
func (rca *RestClientAgent) vote() (err error) {
	req := rad.Vote{
		AgentID:  rca.id,
		BallotID: rca.scrutin,
		Prefs:    rca.prefs,
		Options:  rca.options,
	}

	// sérialisation de la requête
	url := rca.url + "/vote"
	data, _ := json.Marshal(req)

	// envoi de la requête
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))

	// traitement de la réponse
	if err != nil {
		return
	}
	if resp.StatusCode != http.StatusOK {
		err = fmt.Errorf("[%d] %s", resp.StatusCode, resp.Status)
		return
	}

	return
}

func (rca *RestClientAgent) Start() {
	log.Printf("démarrage de %s", rca.id)

	prefs := make([]cs.Alternative, 0)
	if len(rca.prefs) == 0 {
		prefs = cs.GenerateProfile(1, rca.nbAlts)[0]
		rca.prefs = make([]int, len(prefs))
		for i, pref := range prefs {
			rca.prefs[i] = int(pref)
		}
	}

Balthazar Wilson's avatar
Balthazar Wilson committed
	if len(rca.options) == 0 {
		rca.options = []int{1 + rand.Intn(rca.nbAlts-1)}
	}
Balthazar Wilson's avatar
Balthazar Wilson committed

	err := rca.vote()

	if err != nil {
		log.Fatal(rca.id, "error:", err.Error())
	} else {
		log.Printf("[%s] voted in %s\n", rca.id, rca.scrutin)
	}
}