package model

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

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

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

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

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

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

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

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

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

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

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

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

	if !found {
		return
	}

	return &m, nil
}

func (s *Model) AddHandballZone(req HandballZone) (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) AddHandballChamp(req HandballChamp) (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("handballZones", "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) UpdateHandballChampName(req HandballChamp) (err error) {
	if req.Name == "" {
		err = api.Err{
			Code:  EmptyValue,
			Field: "name",
		}
		return
	}

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

func (s *Model) AddHandballTeam(req HandballTeam) (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(HandballAlias{
		Name:   req.CanonicalName,
		TeamID: req.TeamID,
	})
	if err != nil {
		return
	}

	err = tx.Commit()
	return
}

func (s *Model) AddHandballTeamAlias(req HandballAlias) (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("handballTeams", "WHERE teamID=?", req.TeamID)
	if err != nil {
		return
	}

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

	hasAlias, err := tx.Has("handballTeamAliases", "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) SetHandballTeamWasLinked(teamID string) (err error) {
	err = s.qx.Exec(`UPDATE handballTeams SET wasLinked=true WHERE teamID=?`, teamID)
	return
}

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

func (s *Model) AddHandballMatch(req HandballMatch) (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("handballChamps", "WHERE champID=?", req.ChampID)
	if err != nil {
		return
	}

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

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

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

	hasAwayTeam, err := tx.Has("handballTeams", "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 UpdateHandballTeamCanonicalNameIn struct {
	TeamID           string
	CanonicalName    string
	NewCanonicalName string
}

func (s *Model) UpdateHandballTeamCanonicalName(in UpdateHandballTeamCanonicalNameIn) (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 handballTeamAliases WHERE teamID=? AND name=?",
		in.TeamID, in.CanonicalName)
	if err != nil {
		return
	}

	// Обновляем canonicalName
	err = tx.Exec("UPDATE handballTeams 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("handballTeamAliases", "WHERE teamID=? AND name=?",
		in.TeamID, in.NewCanonicalName)
	if err != nil {
		return
	}

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

	err = tx.Commit()
	return
}

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

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

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

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

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

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