package fic

import (
	"fmt"

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

type WorkZoneRoleZQDS struct {
	Name     string        `json:"name"`
	Accesses []interface{} `json:"acceses"`
}

type WorkZoneZQDS struct {
	Name       string             `json:"name"`
	Duplicable bool               `json:"duplicable"`
	Roles      []WorkZoneRoleZQDS `json:"roles"`
}

type ChallengeRequirementsZQDS struct {
	Challenges []string `json:"challenges"`
}

type ChallengeZQDS struct {
	Name            string                     `json:"name"`
	Type            string                     `json:"type,omitempty"`
	Category        string                     `json:"category"`
	Points          int64                      `json:"points"`
	FirstBloodBonus []float64                  `json:"first_blood_bonus,omitempty"`
	Description     string                     `json:"description"`
	Flags           []string                   `json:"flags,omitempty"`
	Requirements    *ChallengeRequirementsZQDS `json:"requirements,omitempty"`
}

type SessionZQDS struct {
	Name          string           `json:"name"`
	BackgroundURL string           `json:"background_url,omitempty"`
	Description   string           `json:"description"`
	Scenario      string           `json:"scenario,omitempty"`
	YourMission   string           `json:"your_mission"`
	Rules         string           `json:"rules"`
	Duration      string           `json:"duration"`
	WorkZones     []WorkZoneZQDS   `json:"work_zones,omitempty"`
	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 {
			var requirements *ChallengeRequirementsZQDS

			if ex.Depend != nil {
				exdep, err := GetExercice(*ex.Depend)
				if err != nil {
					return nil, fmt.Errorf("unable to find dependancy: %w", err)
				}

				requirements = &ChallengeRequirementsZQDS{}
				requirements.Challenges = append(requirements.Challenges, exdep.Title)
			}

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

	return &SessionZQDS{
		Name:        c.Title,
		Description: c.Description,
		Rules:       c.Rules,
		YourMission: c.YourMission,
		Duration:    fmt.Sprintf("%d:%d:00", c.ExpectedDuration/60, c.ExpectedDuration%60),
		Challenges:  challenges,
	}, nil
}
