package model

import (
	"fmt"
	"strings"
	"web/api"
)

func (s *Model) GetFootballZone(zoneID string) (_ *FootballZone, err error) {
	zone := FootballZone{
		ZoneID: zoneID,
	}

	found, err := s.qx.One(&zone)
	if err != nil {
		return
	}

	if !found {
		return
	}
	return &zone, nil
}

func (s *Model) GetFootballChamp(champID string) (_ *FootballChamp, err error) {
	champ := FootballChamp{
		ChampID: champID,
	}

	found, err := s.qx.One(&champ)
	if err != nil {
		return
	}

	if !found {
		return
	}
	return &champ, nil
}

func (s *Model) GetFootballTeam(teamID string) (_ *FootballTeam, err error) {
	team := FootballTeam{
		TeamID: teamID,
	}

	found, err := s.qx.One(&team)
	if err != nil {
		return
	}

	if !found {
		return
	}
	return &team, nil
}

func (s *Model) GetFootballMatch(matchID string) (_ *FootballMatch, err error) {
	m := FootballMatch{
		MatchID: matchID,
	}

	found, err := s.qx.One(&m)
	if err != nil {
		return
	}

	if !found {
		return
	}

	return &m, nil
}

func (s *Model) AddFootballZone(req FootballZone) (err error) {
	if req.Name == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "name",
		}
		return
	}

	tx, err := s.qx.Tx()
	if err != nil {
		return
	}
	defer tx.Close(&err)

	_, err = tx.Insert(req)
	if err != nil {
		return
	}
	err = tx.Commit()
	return
}

func (s *Model) AddFootballChamp(req FootballChamp) (err error) {
	if req.Name == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "name",
		}
		return
	}

	tx, err := s.qx.Tx()
	if err != nil {
		return
	}
	defer tx.Close(&err)

	has, err := tx.Has("footballZones", "WHERE zoneID=?", req.ZoneID)
	if err != nil {
		return
	}

	if !has {
		err = api.Err{
			Code:  UnknownZone,
			Field: "zoneID",
		}
		return
	}

	_, err = tx.Insert(req)
	if err != nil {
		return
	}
	err = tx.Commit()
	return
}

func (s *Model) UpdateFootballChampName(req FootballChamp) (err error) {
	if req.Name == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "name",
		}
		return
	}

	err = s.qx.Exec("UPDATE footballChamps SET name=? WHERE champID=?", req.Name, req.ChampID)
	if err != nil {
		return
	}
	return
}

func (s *Model) AddFootballTeam(req FootballTeam) (err error) {
	req.CanonicalName = NormalizeNameToAlias(req.CanonicalName)

	if req.CanonicalName == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "canonicalName",
		}
		return
	}

	tx, err := s.qx.Tx()
	if err != nil {
		return
	}
	defer tx.Close(&err)

	_, err = tx.Insert(req)
	if err != nil {
		return
	}

	// Добавляем alias
	_, err = tx.Insert(FootballAlias{
		Name:   req.CanonicalName,
		TeamID: req.TeamID,
	})
	if err != nil {
		return
	}

	err = tx.Commit()
	return
}

func (s *Model) AddFootballTeamAlias(req FootballAlias) (err error) {
	req.AliasID = 0
	req.Name = NormalizeNameToAlias(req.Name)

	if req.Name == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "name",
		}
		return
	}

	tx, err := s.qx.Tx()
	if err != nil {
		return
	}
	defer tx.Close(&err)

	hasTeam, err := tx.Has("footballTeams", "WHERE teamID=?", req.TeamID)
	if err != nil {
		return
	}

	if !hasTeam {
		err = api.Err{
			Code:  UnknownTeam,
			Field: "teamID",
		}
		return
	}

	hasAlias, err := tx.Has("footballTeamAliases", "WHERE teamID=? AND name=?",
		req.TeamID, req.Name)
	if err != nil {
		return
	}

	if hasAlias {
		err = api.Err{
			Code:  Duplicate,
			Field: "name",
		}
		return
	}

	// Добавляем alias
	_, err = tx.Insert(req)
	if err != nil {
		return
	}

	err = tx.Commit()
	return
}

func (s *Model) SetFootballTeamWasLinked(teamID string) (err error) {
	err = s.qx.Exec(`UPDATE footballTeams SET wasLinked=true WHERE teamID=?`, teamID)
	return
}

func (s *Model) RemoveFootballTeamAlias(aliasID int64) (err error) {
	return s.qx.Exec(`DELETE FROM footballTeamAliases WHERE aliasID=?`, aliasID)
}

func (s *Model) AddFootballMatch(req FootballMatch) (err error) {
	tx, err := s.qx.Tx()
	if err != nil {
		return
	}
	defer tx.Close(&err)

	req.MatchID = strings.TrimSpace(req.MatchID)

	if req.MatchID == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "matchID",
		}
		return
	}

	hasChamp, err := tx.Has("footballChamps", "WHERE champID=?", req.ChampID)
	if err != nil {
		return
	}

	if !hasChamp {
		err = api.Err{
			Code:  UnknownChamp,
			Field: "champID",
		}
		return
	}

	hasHomeTeam, err := tx.Has("footballTeams", "WHERE teamID=?", req.HomeTeamID)
	if err != nil {
		return
	}

	if !hasHomeTeam {
		err = api.Err{
			Code:  UnknownTeam,
			Field: "teamID",
		}
		return
	}

	hasAwayTeam, err := tx.Has("footballTeams", "WHERE teamID=?", req.AwayTeamID)
	if err != nil {
		return
	}

	if !hasAwayTeam {
		err = api.Err{
			Code:  UnknownTeam,
			Field: "teamID",
		}
		return
	}

	_, err = tx.Insert(req)
	if err != nil {
		return
	}
	err = tx.Commit()
	return
}

type UpdateFootballTeamCanonicalNameIn struct {
	TeamID           string
	CanonicalName    string
	NewCanonicalName string
}

func (s *Model) UpdateFootballTeamCanonicalName(in UpdateFootballTeamCanonicalNameIn) (err error) {
	tx, err := s.qx.Tx()
	if err != nil {
		return
	}
	defer tx.Close(&err)

	// Старый canonicalName не нормализуем, ибо предполагается что имя мы получили из БД
	in.NewCanonicalName = NormalizeNameToAlias(in.NewCanonicalName)

	if in.NewCanonicalName == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "newCanonicalName",
		}
		return
	}

	// Удаляем старый alias
	err = tx.Exec("DELETE FROM footballTeamAliases WHERE teamID=? AND name=?",
		in.TeamID, in.CanonicalName)
	if err != nil {
		return
	}

	// Обновляем canonicalName
	err = tx.Exec("UPDATE footballTeams SET canonicalName=? WHERE teamID=?",
		in.NewCanonicalName, in.TeamID)
	if err != nil {
		fmt.Printf("old: %q, new: %q, teamID: %s\n", in.CanonicalName,
			in.NewCanonicalName, in.TeamID)

		//return
		err = nil
	}

	hasAlias, err := tx.Has("footballTeamAliases", "WHERE teamID=? AND name=?",
		in.TeamID, in.NewCanonicalName)
	if err != nil {
		return
	}

	if !hasAlias {
		// Добавляем новый alias
		_, err = tx.Insert(FootballAlias{
			Name:   in.NewCanonicalName,
			TeamID: in.TeamID,
		})
		if err != nil {
			return
		}
	}

	err = tx.Commit()
	return
}

func (s *Model) ListFootballZones() (list []FootballZone, err error) {
	err = s.qx.ListBy(&list, `ORDER BY name ASC`)
	if err != nil {
		return
	}
	return
}

func (s *Model) ListFootballTeamCandidates(name string) (matchIDs []string, err error) {
	name = NormalizeNameToAlias(name)

	err = s.qx.ListQuery(&matchIDs,
		`SELECT teamID FROM footballTeamAliases WHERE name=?`, name)
	if err != nil {
		return
	}
	return
}

func (s *Model) ListFootballTeamsByZone(zoneID string) (list []FootballTeam, err error) {
	err = s.qx.ListBy(&list, `WHERE zoneID=? ORDER BY canonicalName ASC`, zoneID)
	if err != nil {
		return
	}
	return
}

func (s *Model) ListFootballTeamAliases(teamID string) (list []FootballAlias, err error) {
	err = s.qx.ListBy(&list, `WHERE teamID=? ORDER BY name ASC`, teamID)
	if err != nil {
		return
	}
	return
}

func (s *Model) ListFootballTeams() (list []FootballTeam, err error) {
	err = s.qx.List(&list)
	if err != nil {
		return
	}
	return
}
