package back

import (
	"errors"
)

type manager struct {
	ID         int32  `json:"ID"`
	Login      string `json:"Login"`
	Password   string `json:"Password"`
	FirstName  string `json:"FirstName"`
	LastName   string `json:"LastName"`
	Patronymic string `json:"Patronymic"`
	Role       string `json:"Rolee"`

	Rows []manager
}

func prepareQueriesManager() []string {
	var e error
	ebox := make([]string, 0)

	queries["Select#Manager#Test"], e = db.Prepare(`SELECT count(*) FROM "Manager"`)
	if e != nil {
		ebox = append(ebox, "Select#Manager#Test - "+e.Error())
	}
	queries["Select#Manager#"], e = db.Prepare(`SELECT "ID", "FirstName", "LastName", "Patronymic", "Role" FROM "Manager" WHERE "Login"=$1 AND "Password"=$2`)
	if e != nil {
		ebox = append(ebox, "Select#Manager# - "+e.Error())
	}
	queries["Select#Manager#ByID"], e = db.Prepare(`SELECT "Login", "Password", "FirstName", "LastName", "Patronymic", "Role" FROM "Manager" WHERE "ID"=$1`)
	if e != nil {
		ebox = append(ebox, "Select#Manager#ByID - "+e.Error())
	}

	queries["Insert#Manager#"], e = db.Prepare(`INSERT INTO "Manager"(
		"Login", "Password", "FirstName", "LastName", "Patronymic", "Role")
		VALUES ($1, $2, $3, $4, $5, $6)`)
	if e != nil {
		ebox = append(ebox, "Insert#Manager# - "+e.Error())
	}

	return ebox
}

func (m *manager) SelectTest() error {
	stmt, ok := queries["Select#Manager#Test"]
	if !ok {
		return errors.New("Запрос Select#Manager#Test не найден")
	}

	count := int32(0)

	r := stmt.QueryRow()
	e := r.Scan(&count)
	if e != nil {
		return e
	}

	if count == 0 {
		stmt, ok = queries["Insert#Manager#"]
		if !ok {
			return errors.New("Запрос Insert#Manager# не найден")
		}

		stmt.Exec("8009008070", "!@#$%^&*", "Administrator", "", "", "__admin")
	}

	return errors.New("YES")
}

func (m *manager) Select() error {
	stmt, ok := queries["Select#Manager#"]
	if !ok {
		return errors.New("Запрос Select#Manager# не найден")
	}

	r := stmt.QueryRow(m.Login, m.Password)
	e := r.Scan(&m.ID, &m.FirstName, &m.LastName, &m.Patronymic, &m.Role)
	if e != nil {
		return e
	}

	return nil
}

func (m *manager) SelectByID() error {
	stmt, ok := queries["Select#Manager#ByID"]
	if !ok {
		return errors.New("Запрос Select#Manager#ByID не найден")
	}

	r := stmt.QueryRow(m.ID)
	e := r.Scan(&m.Login, &m.Password, &m.FirstName, &m.LastName, &m.Patronymic, &m.Role)
	if e != nil {
		return e
	}

	return nil
}
