package fic

import (
	"fmt"
	"time"

	"srs.epita.fr/fic-server/settings"
)

type ChallengeZQDS struct {
	ID              int64     `json:"id,omitempty"`
	Name            string    `json:"name"`
	Type            string    `json:"type,omitempty"`
	Category        string    `json:"category"`
	Points          int64     `json:"points"`
	State           string    `json:"state"`
	LockedBy        []int64   `json:"locked_by,omitempty"`
	FirstBloodBonus []float64 `json:"first_blood_bonus,omitempty"`
	Description     string    `json:"description"`
	Flags           []string  `json:"flags,omitempty"`
}

type SessionZQDS struct {
	Name        string           `json:"name"`
	Description string           `json:"description"`
	Scenario    string           `json:"scenario,omitempty"`
	YourMission string           `json:"your_mission"`
	Rules       string           `json:"rules"`
	Start       time.Time        `json:"start"`
	End         time.Time        `json:"end"`
	Challenges  []*ChallengeZQDS `json:"challenges"`
}

func GenZQDSSessionFile(c *settings.ChallengeInfo, s *settings.Settings) (*SessionZQDS, error) {
	themes, err := GetThemes()
	if err != nil {
		return nil, err
	}

	if s.End == nil {
		return nil, fmt.Errorf("Please define an end date")
	}

	var challenges []*ChallengeZQDS

	for _, th := range themes {
		exos, err := th.GetExercices()
		if err != nil {
			return nil, err
		}

		for _, ex := range exos {
			state := "visible"
			lockedby := []int64{}

			if ex.Depend != nil {
				state = "locked"
				lockedby = append(lockedby, *ex.Depend)
			}

			challenges = append(challenges, &ChallengeZQDS{
				ID:       ex.Id,
				Name:     ex.Title,
				Type:     "first_blood",
				Category: th.Name,
				Points:   ex.Gain,
				State:    state,
				LockedBy: lockedby,
				FirstBloodBonus: []float64{
					float64(ex.Gain) * (1 + s.FirstBlood),
				},
				Description: ex.Overview,
			})
		}
	}

	return &SessionZQDS{
		Name:        c.Title,
		Description: c.Description,
		Rules:       c.Rules,
		YourMission: c.YourMission,
		Start:       s.Start,
		End:         *s.End,
		Challenges:  challenges,
	}, nil
}
