package fic

import (
	"log"
	"math"
	"time"

	"golang.org/x/crypto/bcrypt"
)

// UnlockedChallengeDepth is the number of challenges to unlock ahead (0: only the next one, -1: all)
var UnlockedChallengeDepth int

// UnlockedChallengeUpTo is the number of level to unlock
var UnlockedChallengeUpTo int

// WchoiceCoefficient is the current coefficient applied on the cost of changing flag into choices
var WChoiceCoefficient = 1.0

// Team represents a group of players, come to solve our challenges.
type Team struct {
	Id         int64   `json:"id"`
	Name       string  `json:"name"`
	Color      uint32  `json:"color"`
	Active     bool    `json:"active"`
	ExternalId string  `json:"external_id"`
	Password   *string `json:"password"`
}

func getTeams(filter string) ([]*Team, error) {
	if rows, err := DBQuery("SELECT id_team, name, color, active, external_id, password FROM teams " + filter); err != nil {
		return nil, err
	} else {
		defer rows.Close()

		var teams []*Team
		for rows.Next() {
			t := &Team{}
			if err := rows.Scan(&t.Id, &t.Name, &t.Color, &t.Active, &t.ExternalId, &t.Password); err != nil {
				return nil, err
			}
			teams = append(teams, t)
		}
		if err := rows.Err(); err != nil {
			return nil, err
		}

		return teams, nil
	}
}

// GetTeams returns a list of registered Team from the database.
func GetTeams() ([]*Team, error) {
	return getTeams("")
}

// GetActiveTeams returns a list of registered Team from the database, limited to team to generate.
func GetActiveTeams() ([]*Team, error) {
	return getTeams("WHERE active = 1")
}

// GetTeam retrieves a Team from its identifier.
func GetTeam(id int64) (*Team, error) {
	t := &Team{}
	if err := DBQueryRow("SELECT id_team, name, color, active, external_id, password FROM teams WHERE id_team = ?", id).Scan(&t.Id, &t.Name, &t.Color, &t.Active, &t.ExternalId, &t.Password); err != nil {
		return t, err
	}

	return t, nil
}

// GetTeamBySerial retrieves a Team from one of its associated certificates.
func GetTeamBySerial(serial int64) (*Team, error) {
	t := &Team{}
	if err := DBQueryRow("SELECT T.id_team, T.name, T.color, T.active, T.external_id, T.password FROM certificates C INNER JOIN teams T ON T.id_team = C.id_team WHERE id_cert = ?", serial).Scan(&t.Id, &t.Name, &t.Color, &t.Active, &t.ExternalId, &t.Password); err != nil {
		return t, err
	}

	return t, nil
}

// CreateTeam creates and fills a new struct Team and registers it into the database.
func CreateTeam(name string, color uint32, externalId string) (*Team, error) {
	if res, err := DBExec("INSERT INTO teams (name, color, external_id) VALUES (?, ?, ?)", name, color, externalId); err != nil {
		return nil, err
	} else if tid, err := res.LastInsertId(); err != nil {
		return nil, err
	} else {
		return &Team{tid, name, color, true, "", nil}, nil
	}
}

// Update applies modifications back to the database.
func (t *Team) Update() (int64, error) {
	if res, err := DBExec("UPDATE teams SET name = ?, color = ?, active = ?, external_id = ?, password = ? WHERE id_team = ?", t.Name, t.Color, t.Active, t.ExternalId, t.Password, t.Id); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}

// Delete the challenge from the database
func (t *Team) Delete() (int64, error) {
	if _, err := DBExec("DELETE FROM team_members WHERE id_team = ?", t.Id); err != nil {
		return 0, err
	} else if res, err := DBExec("DELETE FROM teams WHERE id_team = ?", t.Id); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}

// HasAccess checks if the Team has access to the given challenge.
func (t *Team) HasAccess(e *Exercice) bool {
	// Case of standalone exercices
	if e.IdTheme == nil || *e.IdTheme == 0 {
		ord, err := e.GetOrdinal()
		if err != nil {
			return false
		}

		if ord < UnlockedStandaloneExercices {
			return true
		}

		nbsteps, nbexos, err := t.SolvedCount()
		if nbsteps == nil || nbexos == nil || err != nil {
			return false
		}

		if ord < UnlockedStandaloneExercices+int(math.Floor(UnlockedStandaloneExercicesByThemeStepValidation*float64(*nbsteps)))+int(math.Floor(UnlockedStandaloneExercicesByStandaloneExerciceValidation*float64(*nbexos))) {
			return true
		}

		return false
	}

	if UnlockedChallengeDepth < 0 {
		return true
	}

	if UnlockedChallengeUpTo > 1 {
		lvl, err := e.GetLevel()
		if err == nil && lvl <= UnlockedChallengeUpTo {
			return true
		}
	}

	for i := UnlockedChallengeDepth; i >= 0; i-- {
		// An exercice without dependency is accessible
		if e.Depend == nil {
			return true
		}

		ed := &Exercice{}
		ed.Id = *e.Depend
		s := t.HasSolved(ed)
		if s != nil {
			return true
		}

		// Prepare next iteration
		var err error
		e, err = GetExercice(ed.Id)
		if err != nil {
			return false
		}

		// If our previous exercice is WIP, unlock
		if i == UnlockedChallengeDepth && e.WIP {
			return true
		}

	}
	return false
}

// CanDownload checks if the Team has access to the given file.
func (t *Team) CanDownload(f *EFile) bool {
	if !f.Published {
		return false
	} else if deps, err := f.GetDepends(); err != nil {
		log.Printf("Unable to retrieve file dependencies: %s\n", err)
		return false
	} else {
		res := true

		for _, dep := range deps {
			if t.HasPartiallySolved(dep) == nil {
				res = false
				break
			}
		}

		return res
	}
}

// CanSeeHint checks if the Team has access to the given hint.
func (t *Team) CanSeeHint(h *EHint) bool {
	if deps, err := h.GetDepends(); err != nil {
		log.Printf("Unable to retrieve flag dependencies: %s\n", err)
		return false
	} else {
		res := true

		for _, dep := range deps {
			if t.HasPartiallySolved(dep) == nil {
				res = false
				break
			}
		}

		return res
	}
}

// CanSeeFlag checks if the Team has access to the given flag.
func (t *Team) CanSeeFlag(k Flag) bool {
	if deps, err := k.GetDepends(); err != nil {
		log.Printf("Unable to retrieve flag dependencies: %s\n", err)
		return false
	} else {
		res := true

		for _, dep := range deps {
			if t.HasPartiallySolved(dep) == nil {
				res = false
				break
			}
		}

		return res
	}
}

// NbTry retrieves the number of attempts made by the Team to the given challenge.
func NbTry(t *Team, e *Exercice) int {
	tries_table := "exercice_tries"
	if SubmissionUniqueness {
		tries_table = "exercice_distinct_tries"
	}
	if CountOnlyNotGoodTries {
		tries_table += "_notgood"
	}

	var cnt *int

	if t != nil {
		DBQueryRow("SELECT COUNT(*) FROM "+tries_table+" WHERE id_team = ? AND id_exercice = ?", t.Id, e.Id).Scan(&cnt)
	} else {
		DBQueryRow("SELECT COUNT(*) FROM "+tries_table+" WHERE id_exercice = ?", e.Id).Scan(&cnt)
	}

	if cnt == nil {
		return 0
	} else {
		return *cnt
	}
}

// HasHint checks if the Team has revealed the given Hint.
func (t *Team) HasHint(h *EHint) bool {
	var tm *time.Time
	DBQueryRow("SELECT MIN(time) FROM team_hints WHERE id_team = ? AND id_hint = ?", t.Id, h.Id).Scan(&tm)
	return tm != nil
}

// OpenHint registers to the database that the Team has now revealed.
func (t *Team) OpenHint(h *EHint) error {
	_, err := DBExec("INSERT INTO team_hints (id_team, id_hint, time, coefficient) VALUES (?, ?, ?, ?)", t.Id, h.Id, time.Now(), math.Max(HintCoefficient, 0.0))
	return err
}

// SeeChoices checks if the Team has revealed the given choices.
func (t *Team) SeeChoices(k *FlagKey) bool {
	var tm *time.Time
	DBQueryRow("SELECT MIN(time) FROM team_wchoices WHERE id_team = ? AND id_flag = ?", t.Id, k.Id).Scan(&tm)
	return tm != nil
}

// DisplayChoices registers to the database that the Team has now revealed.
func (t *Team) DisplayChoices(k *FlagKey) error {
	_, err := DBExec("INSERT INTO team_wchoices (id_team, id_flag, time, coefficient) VALUES (?, ?, ?, ?)", t.Id, k.Id, time.Now(), math.Max(WChoiceCoefficient, 0.0))
	return err
}

// CountTries gets the amount of attempts made by the Team and retrieves the time of the latest attempt.
func (t *Team) CountTries(e *Exercice) (nb int64, tm *time.Time) {
	table := "exercice_tries"
	if SubmissionUniqueness {
		table = "exercice_distinct_tries"
	}
	if CountOnlyNotGoodTries {
		table += "_notgood"
	}

	DBQueryRow("SELECT COUNT(id_exercice), MAX(time) FROM "+table+" WHERE id_team = ? AND id_exercice = ?", t.Id, e.Id).Scan(&nb, &tm)

	// time is not accurate in distinct nor _notgood tables as it only considers notgood or distincts answers, so the last try is not count
	if SubmissionUniqueness || CountOnlyNotGoodTries {
		DBQueryRow("SELECT MAX(time) FROM exercice_tries WHERE id_team = ? AND id_exercice = ?", t.Id, e.Id).Scan(&tm)
	}

	return
}

// LastTryDist retrieves the distance to the correct answers, for the given challenge.
// The distance is the number of bad responses given in differents MCQs.
func (t *Team) LastTryDist(e *Exercice) int64 {
	var nb *int64
	if DBQueryRow("SELECT nbdiff FROM exercice_tries WHERE id_team = ? AND id_exercice = ? ORDER BY time DESC LIMIT 1", t.Id, e.Id).Scan(&nb); nb == nil {
		return 0
	} else {
		return *nb
	}
}

// SolvedCount returns the number of solved exercices.
func (t *Team) SolvedCount() (nbsteps *int64, nbex *int64, err error) {
	err = DBQueryRow("SELECT COUNT(S.id_exercice) FROM exercice_solved S INNER JOIN exercices E ON E.id_exercice = S.id_exercice WHERE S.id_team = ? AND E.id_theme IS NOT NULL", t.Id).Scan(&nbsteps)
	if err != nil {
		return
	}

	err = DBQueryRow("SELECT COUNT(S.id_exercice) FROM exercice_solved S INNER JOIN exercices E ON E.id_exercice = S.id_exercice WHERE S.id_team = ? AND E.id_theme IS NULL", t.Id).Scan(&nbex)
	return
}

// HasSolved checks if the Team already has validated the given challenge.
// Note that the function also returns the effective validation timestamp.
func (t *Team) HasSolved(e *Exercice) (tm *time.Time) {
	DBQueryRow("SELECT time FROM exercice_solved WHERE id_team = ? AND id_exercice = ? ORDER BY time ASC LIMIT 1", t.Id, e.Id).Scan(&tm)
	return
}

// GetSolvedRank returns the number of teams that solved the challenge before the Team.
func (t *Team) GetSolvedRank(e *Exercice) (nb int64, err error) {
	if rows, errr := DBQuery("SELECT id_team FROM exercice_solved WHERE id_exercice = ? ORDER BY time ASC", e.Id); errr != nil {
		return nb, errr
	} else {
		defer rows.Close()

		for rows.Next() {
			var tid int64
			if err = rows.Scan(&tid); err != nil {
				return
			}

			nb += 1
			if t.Id == tid {
				break
			}
		}
		return
	}
}

// HasPartiallySolved checks if the Team already has unlocked the given flag and returns the validation's timestamp.
func (t *Team) HasPartiallySolved(f Flag) (tm *time.Time) {
	if _, ok := f.(*FlagLabel); ok {
		now := time.Now()
		return &now
	} else if k, ok := f.(*FlagKey); ok {
		DBQueryRow("SELECT MIN(time) FROM flag_found WHERE id_team = ? AND id_flag = ?", t.Id, k.Id).Scan(&tm)
	} else if m, ok := f.(*MCQ); ok {
		DBQueryRow("SELECT MIN(time) FROM mcq_found WHERE id_team = ? AND id_mcq = ?", t.Id, m.Id).Scan(&tm)
	} else {
		log.Fatal("Unknown flag type")
	}
	return
}

// HashedPassword compute a bcrypt version of the team's password.
func (t *Team) HashedPassword() (string, error) {
	if t.Password == nil {
		if passwd, err := GeneratePassword(); err != nil {
			return "", err
		} else {
			h, err := bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
			return string(h), err
		}
	}

	h, err := bcrypt.GenerateFromPassword([]byte(*t.Password), bcrypt.DefaultCost)
	return string(h), err
}
