package fic

import (
	"errors"
	"fmt"
	"math"
	"time"
)

// PartialValidation allows a Team to validate an Exercice at a given point if
// it has ever found all classical flags, even if the last validation is not
// complete or contains mistakes on previously validated flags.
var PartialValidation bool

// PartialMCQValidation allows a Team to validate each MCQ independently.
// Otherwise, all MCQ has to be correct for being validated.
var PartialMCQValidation bool

// ExerciceCurrentCoefficient is the current coefficient applied on solved exercices
var ExerciceCurrentCoefficient = 1.0

// Exercice represents a challenge inside a Theme.
type Exercice struct {
	Id       int64  `json:"id"`
	IdTheme  int64  `json:"id_theme"`
	Language string `json:"lang,omitempty"`
	Title    string `json:"title"`
	Authors  string `json:"authors"`
	Image    string `json:"image"`
	// Disabled indicates if the exercice is available to players now or not
	Disabled bool `json:"disabled"`
	// WIP indicates if the exercice is in development or not
	WIP bool `json:"wip"`
	// URLid is used to reference the challenge from the URL path
	URLId string `json:"urlid"`
	// Path is the relative import location where find challenge data
	Path string `json:"path"`
	// Statement is the challenge description shown to players
	Statement string `json:"statement"`
	// Overview is the challenge description shown to public
	Overview string `json:"overview"`
	// Headline is the challenge headline to fill in small part
	Headline string `json:"headline"`
	// Finished is the text shown when the exercice is solved
	Finished string `json:"finished"`
	// Issue is an optional text describing an issue with the exercice
	Issue string `json:"issue"`
	// IssueKind is the criticity level of the previous issue
	IssueKind string `json:"issuekind"`
	Depend    *int64 `json:"depend"`
	// Gain is the basis amount of points player will earn if it solve the challenge
	// If this value fluctuate during the challenge, players' scores will follow changes.
	// Use Coefficient value to create temporary bonus/malus.
	Gain int64 `json:"gain"`
	// Coefficient is a temporary bonus/malus applied on Gain when the challenge is solved.
	// This value is saved along with solved informations: changing it doesn't affect Team that already solved the challenge.
	Coefficient float64 `json:"coefficient"`
	// VideoURI is the link to the resolution video
	VideoURI string `json:"videoURI"`
	// Resolution is a write-up (in HTML)
	Resolution string `json:"resolution"`
	// SeeAlso is a collection of links (HTML formated)
	SeeAlso string `json:"seealso"`
}

func (e *Exercice) AnalyzeTitle() {
	if len(e.Title) > 0 && e.Title[0] == '%' {
		e.WIP = true
		e.Title = e.Title[1:]
	} else {
		e.WIP = false
	}
}

func getExercice(table, condition string, args ...interface{}) (*Exercice, error) {
	var e Exercice
	var tmpgain float64
	if err := DBQueryRow("SELECT id_exercice, id_theme, title, authors, image, disabled, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, resolution, seealso, finished FROM "+table+" "+condition, args...).Scan(&e.Id, &e.IdTheme, &e.Title, &e.Authors, &e.Image, &e.Disabled, &e.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &tmpgain, &e.Coefficient, &e.VideoURI, &e.Resolution, &e.SeeAlso, &e.Finished); err != nil {
		return nil, err
	}
	e.Gain = int64(math.Trunc(tmpgain))
	e.AnalyzeTitle()

	return &e, nil
}

// GetExercice retrieves the challenge with the given id.
func GetExercice(id int64) (*Exercice, error) {
	return getExercice("exercices", "WHERE id_exercice = ?", id)
}

// GetExercice retrieves the challenge with the given id.
func (t *Theme) GetExercice(id int) (*Exercice, error) {
	return getExercice("exercices", "WHERE id_theme = ? AND id_exercice = ?", t.Id, id)
}

// GetExerciceByTitle retrieves the challenge with the given title.
func (t *Theme) GetExerciceByTitle(title string) (*Exercice, error) {
	return getExercice("exercices", "WHERE id_theme = ? AND title = ?", t.Id, title)
}

// GetExerciceByPath retrieves the challenge with the given path.
func (t *Theme) GetExerciceByPath(epath string) (*Exercice, error) {
	return getExercice("exercices", "WHERE id_theme = ? AND path = ?", t.Id, epath)
}

// GetDiscountedExercice retrieves the challenge with the given id.
func GetDiscountedExercice(id int64) (*Exercice, error) {
	table := "exercices"
	if DiscountedFactor > 0 {
		table = "exercices_discounted"
	}
	return getExercice(table, "WHERE id_exercice = ?", id)
}

// getExercices returns the list of all challenges present in the database.
func getExercices(table string) ([]*Exercice, error) {
	if rows, err := DBQuery("SELECT id_exercice, id_theme, title, authors, image, disabled, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, resolution, seealso, finished FROM " + table + " ORDER BY path ASC"); err != nil {
		return nil, err
	} else {
		defer rows.Close()

		exos := []*Exercice{}
		for rows.Next() {
			e := &Exercice{}
			var tmpgain float64
			if err := rows.Scan(&e.Id, &e.IdTheme, &e.Title, &e.Authors, &e.Image, &e.Disabled, &e.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &tmpgain, &e.Coefficient, &e.VideoURI, &e.Resolution, &e.SeeAlso, &e.Finished); err != nil {
				return nil, err
			}
			e.Gain = int64(math.Trunc(tmpgain))
			e.AnalyzeTitle()
			exos = append(exos, e)
		}
		if err := rows.Err(); err != nil {
			return nil, err
		}

		return exos, nil
	}
}

func GetExercices() ([]*Exercice, error) {
	return getExercices("exercices")
}

func GetDiscountedExercices() ([]*Exercice, error) {
	table := "exercices"
	if DiscountedFactor > 0 {
		table = "exercices_discounted"
	}
	return getExercices(table)
}

// GetExercices returns the list of all challenges in the Theme.
func (t *Theme) GetExercices() ([]*Exercice, error) {
	if rows, err := DBQuery("SELECT id_exercice, id_theme, title, authors, image, disabled, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, resolution, seealso, finished FROM exercices WHERE id_theme = ? ORDER BY path ASC", t.Id); err != nil {
		return nil, err
	} else {
		defer rows.Close()

		exos := []*Exercice{}
		for rows.Next() {
			e := &Exercice{}
			if err := rows.Scan(&e.Id, &e.IdTheme, &e.Title, &e.Authors, &e.Image, &e.Disabled, &e.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &e.Gain, &e.Coefficient, &e.VideoURI, &e.Resolution, &e.SeeAlso, &e.Finished); err != nil {
				return nil, err
			}
			e.AnalyzeTitle()
			exos = append(exos, e)
		}
		if err := rows.Err(); err != nil {
			return nil, err
		}

		return exos, nil
	}
}

// SaveNamedExercice looks for an exercice with the same title to update it, or create it if it doesn't exists yet.
func (t *Theme) SaveNamedExercice(e *Exercice) (err error) {
	var search *Exercice

	// Search same title
	search, _ = t.GetExerciceByTitle(e.Title)

	// Search on same path
	if search == nil && len(e.Path) > 0 {
		search, err = t.GetExerciceByPath(e.Path)
	}

	if search == nil {
		err = t.addExercice(e)
	} else {
		// Force ID
		e.Id = search.Id

		// Don't expect those values
		if e.Coefficient == 0 {
			e.Coefficient = search.Coefficient
		}
		if len(e.Issue) == 0 {
			e.Issue = search.Issue
		}
		if len(e.IssueKind) == 0 {
			e.IssueKind = search.IssueKind
		}

		_, err = e.Update()
	}
	return
}

func (t *Theme) addExercice(e *Exercice) (err error) {
	var ik = "DEFAULT"
	if len(e.IssueKind) > 0 {
		ik = fmt.Sprintf("%q", e.IssueKind)
	}

	var cc = "DEFAULT"
	if e.Coefficient != 0 {
		cc = fmt.Sprintf("%f", e.Coefficient)
	}

	wip := ""
	if e.WIP {
		wip = "%"
	}
	if res, err := DBExec("INSERT INTO exercices (id_theme, title, authors, image, disabled, url_id, path, statement, overview, finished, headline, issue, depend, gain, video_uri, resolution, seealso, issue_kind, coefficient_cur) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "+ik+", "+cc+")", t.Id, wip+e.Title, e.Authors, e.Image, e.Disabled, e.URLId, e.Path, e.Statement, e.Overview, e.Finished, e.Headline, e.Issue, e.Depend, e.Gain, e.VideoURI, e.Resolution, e.SeeAlso); err != nil {
		return err
	} else if eid, err := res.LastInsertId(); err != nil {
		return err
	} else {
		e.Id = eid

		return nil
	}
}

// AddExercice creates and fills a new struct Exercice and registers it into the database.
func (t *Theme) AddExercice(title string, authors string, image string, wip bool, urlId string, path string, statement string, overview string, headline string, depend *Exercice, gain int64, videoURI string, resolution string, seealso string, finished string) (e *Exercice, err error) {
	var dpd *int64 = nil
	if depend != nil {
		dpd = &depend.Id
	}

	e = &Exercice{
		Title:      title,
		Authors:    authors,
		Image:      image,
		Disabled:   false,
		WIP:        wip,
		URLId:      urlId,
		Path:       path,
		Statement:  statement,
		Overview:   overview,
		Headline:   headline,
		Depend:     dpd,
		Finished:   finished,
		Gain:       gain,
		VideoURI:   videoURI,
		Resolution: resolution,
		SeeAlso:    seealso,
	}

	err = t.addExercice(e)

	return
}

// Update applies modifications back to the database.
func (e *Exercice) Update() (int64, error) {
	wip := ""
	if e.WIP {
		wip = "%"
	}

	if res, err := DBExec("UPDATE exercices SET title = ?, authors = ?, image = ?, disabled = ?, url_id = ?, path = ?, statement = ?, overview = ?, headline = ?, issue = ?, issue_kind = ?, depend = ?, gain = ?, coefficient_cur = ?, video_uri = ?, resolution = ?, seealso = ?, finished = ? WHERE id_exercice = ?", wip+e.Title, e.Authors, e.Image, e.Disabled, e.URLId, e.Path, e.Statement, e.Overview, e.Headline, e.Issue, e.IssueKind, e.Depend, e.Gain, e.Coefficient, e.VideoURI, e.Resolution, e.SeeAlso, e.Finished, e.Id); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}

// FixURLId generates a valid URLid from the challenge Title.
// It returns true if something has been generated.
func (e *Exercice) FixURLId() bool {
	if e.URLId == "" {
		e.URLId = ToURLid(e.Title)
		return true
	}
	return false
}

// Delete the challenge from the database.
func (e *Exercice) Delete() (int64, error) {
	if res, err := DBExec("DELETE FROM exercices WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}

// DeleteCascade the challenge from the database, including inner content but not player content.
func (e *Exercice) DeleteCascade() (int64, error) {
	if _, err := DBExec("UPDATE exercices SET depend = NULL WHERE depend = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_files_okey_deps WHERE id_file IN (SELECT id_file FROM exercice_files WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_files_omcq_deps WHERE id_file IN (SELECT id_file FROM exercice_files WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_files WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_hints_okey_deps WHERE id_hint IN (SELECT id_hint FROM exercice_hints WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_hints_omcq_deps WHERE id_hint IN (SELECT id_hint FROM exercice_hints WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_hints WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_flags_deps WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM flag_choices WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM mcq_entries WHERE id_mcq IN (SELECT id_mcq FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_mcq WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_tags WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM teams_qa_todo WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM teams_qa_view WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else {
		return e.Delete()
	}
}

// DeleteCascadePlayer delete player content related to this challenge.
func (e *Exercice) DeleteCascadePlayer() (int64, error) {
	if _, err := DBExec("DELETE FROM mcq_found WHERE id_mcq IN (SELECT id_mcq FROM exercice_mcq WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM flag_found WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM team_hints WHERE id_hint IN (SELECT id_hint FROM exercice_hints WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM team_wchoices WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_solved WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if _, err := DBExec("DELETE FROM exercice_tries WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else {
		return 1, nil
	}
}

// DeleteDeep the challenge from the database, including player content.
func (e *Exercice) DeleteDeep() (int64, error) {
	if _, err := e.DeleteCascadePlayer(); err != nil {
		return 0, err
	} else {
		return e.DeleteCascade()
	}
}

// GetLevel returns the number of dependancy challenges.
func (e *Exercice) GetLevel() (int, error) {
	dep := e.Depend
	nb := 1
	for dep != nil {
		nb += 1
		if nb > 10 || *dep == e.Id {
			return nb, errors.New("exceed number of levels")
		} else if edep, err := GetExercice(*dep); err != nil {
			return nb, err
		} else {
			dep = edep.Depend
		}
	}
	return nb, nil
}

// NewTry registers a solving attempt for the given Team.
func (e *Exercice) NewTry(t *Team, cksum []byte) error {
	if _, err := DBExec("INSERT INTO exercice_tries (id_exercice, id_team, time, cksum) VALUES (?, ?, ?, ?)", e.Id, t.Id, time.Now(), cksum); err != nil {
		return err
	} else {
		return nil
	}
}

// UpdateTry applies modifications to the latest try registered for the given Team.
// Updated values are time and the given nbdiff.
func (e *Exercice) UpdateTry(t *Team, nbdiff int, oneGood bool) error {
	if _, err := DBExec("UPDATE exercice_tries SET nbdiff = ?, onegood = ?, time = ? WHERE id_exercice = ? AND id_team = ? ORDER BY time DESC LIMIT 1", nbdiff, oneGood, time.Now(), e.Id, t.Id); err != nil {
		return err
	} else {
		return nil
	}
}

// Solved registers that the given Team solves the challenge.
func (e *Exercice) Solved(t *Team) error {
	if _, err := DBExec("INSERT INTO exercice_solved (id_exercice, id_team, time, coefficient) VALUES (?, ?, ?, ?)", e.Id, t.Id, time.Now(), e.Coefficient*ExerciceCurrentCoefficient); err != nil {
		return err
	} else {
		return nil
	}
}

// SolvedCount returns the number of Team that already have solved the challenge.
func (e *Exercice) SolvedCount() int64 {
	var nb int64
	if err := DBQueryRow("SELECT COUNT(id_exercice) FROM exercice_solved WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil {
		return 0
	} else {
		return nb
	}
}

// TriedTeamCount returns the number of Team that attempted to solve the exercice.
func (e *Exercice) TriedTeamCount() int64 {
	tries_table := "exercice_tries"
	if SubmissionUniqueness {
		tries_table = "exercice_distinct_tries"
	}

	var nb int64
	if err := DBQueryRow("SELECT COUNT(DISTINCT id_team) FROM "+tries_table+" WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil {
		return 0
	} else {
		return nb
	}
}

// TriedCount returns the number of cumulative attempts, all Team combined, for the exercice.
func (e *Exercice) TriedCount() int64 {
	tries_table := "exercice_tries"
	if SubmissionUniqueness {
		tries_table = "exercice_distinct_tries"
	}

	var nb int64
	if err := DBQueryRow("SELECT COUNT(id_team) FROM "+tries_table+" WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil {
		return 0
	} else {
		return nb
	}
}

// FlagSolved returns the list of flags solved.
func (e *Exercice) FlagSolved() (res []int64) {
	if rows, err := DBQuery("SELECT F.id_flag FROM flag_found F INNER JOIN exercice_flags E ON E.id_flag = F.id_flag WHERE E.id_exercice = ? GROUP BY id_flag", e.Id); err != nil {
		return
	} else {
		defer rows.Close()

		for rows.Next() {
			var n int64
			if err := rows.Scan(&n); err != nil {
				return
			}
			res = append(res, n)
		}
		return
	}
}

// MCQSolved returns the list of mcqs solved.
func (e *Exercice) MCQSolved() (res []int64) {
	if rows, err := DBQuery("SELECT F.id_mcq FROM mcq_found F INNER JOIN exercice_mcq E ON E.id_mcq = F.id_mcq WHERE E.id_exercice = ? GROUP BY id_mcq", e.Id); err != nil {
		return
	} else {
		defer rows.Close()

		for rows.Next() {
			var n int64
			if err := rows.Scan(&n); err != nil {
				return
			}
			res = append(res, n)
		}
		return
	}
}

// CheckResponse, given both flags and MCQ responses, figures out if thoses are correct (or if they are previously solved).
// In the meanwhile, CheckResponse registers good answers given (but it does not mark the challenge as solved at the end).
func (e *Exercice) CheckResponse(cksum []byte, respflags map[int]string, respmcq map[int]bool, t *Team) (bool, error) {
	if err := e.NewTry(t, cksum); err != nil {
		return false, err
	} else if flags, err := e.GetFlagKeys(); err != nil {
		return false, err
	} else if mcqs, err := e.GetMCQ(); err != nil {
		return false, err
	} else if len(flags) < 1 && len(mcqs) < 1 {
		return true, errors.New("Exercice with no flag registered")
	} else {
		valid := true
		diff := 0
		goodResponses := 0

		// Check MCQs
		for _, mcq := range mcqs {
			if d := mcq.Check(respmcq); d > 0 {
				if !PartialValidation || t.HasPartiallySolved(mcq) == nil {
					valid = false
					diff += d
				}
			} else if !PartialMCQValidation && d == 0 {
				mcq.FoundBy(t)
				goodResponses += 1
			}
		}

		// Validate MCQs if no error
		if valid {
			for _, mcq := range mcqs {
				if mcq.FoundBy(t) == nil {
					goodResponses += 1
				}
			}
		}

		// Check flags
		for _, flag := range flags {
			if res, ok := respflags[flag.Id]; !ok && (!PartialValidation || t.HasPartiallySolved(flag) == nil) {
				valid = valid && flag.IsOptionnal()
			} else if flag.Check([]byte(res)) != 0 {
				if !PartialValidation || t.HasPartiallySolved(flag) == nil {
					valid = valid && flag.IsOptionnal()
				}
			} else {
				flag.FoundBy(t)
				goodResponses += 1
			}
		}

		if diff > 0 || goodResponses > 0 {
			e.UpdateTry(t, diff, goodResponses > 0)
		}

		return valid, nil
	}
}

// IsSolved returns the number of time this challenge has been solved and the time of the first solve occurence.
func (e *Exercice) IsSolved() (int, *time.Time) {
	var nb *int
	var tm *time.Time
	if DBQueryRow("SELECT COUNT(id_exercice), MIN(time) FROM exercice_solved WHERE id_exercice = ?", e.Id).Scan(&nb, &tm); nb == nil || tm == nil {
		return 0, nil
	} else {
		return *nb, tm
	}
}
