package back

import "errors"

// InformationMass

type informationMass struct {
	Infa string `json:"Link"`

	Rows []string
}

func prepareInfa() []string {
	var e error
	var elist []string

	queries["Insert@Infa@"], e = db.Prepare(`INSERT INTO "InformationMass" ("infa", "published") VALUES($1, CURRENT_TIMESTAMP)`)
	if e != nil {
		elist = append(elist, e.Error())
	}

	queries["Select@Infa@"], e = db.Prepare(`SELECT "infa" FROM "InformationMass" ORDER BY "published" DESC`)
	if e != nil {
		elist = append(elist, e.Error())
	}

	queries["Insert@Record@"], e = db.Prepare(`INSERT INTO "Record"("Name", "Passport", "Phone", "Cause") VALUES ($1, $2, $3, $4) RETURNING "ID"`)
	if e != nil {
		elist = append(elist, "[Insert@Record@] - "+e.Error())
	}

	queries["Insert@TimeRecord@"], e = db.Prepare(`INSERT INTO "TimeRecord"("Date", "Time", "Record") VALUES($1, $2, $3)`)
	if e != nil {
		elist = append(elist, "[Insert@TimeRecord@] - "+e.Error())
	}

	queries["Update@TimeRecord@"], e = db.Prepare(`UPDATE "TimeRecord" SET "Record"=$1 WHERE "Date"=$2 AND "Time"=$3`)
	if e != nil {
		elist = append(elist, "[Insert@TimeRecord@] - "+e.Error())
	}

	queries["Select@TimeRecord@Times"], e = db.Prepare(`SELECT "Time" FROM "TimeRecord" WHERE "Date"=$1 AND "Record" IS NULL`)
	if e != nil {
		elist = append(elist, "[Select@TimeRecord@Times] - "+e.Error())
	}

	queries["Select#Order#"], e = db.Prepare(`SELECT o."ID", o."Name", o."Passport", o."Phone", o."Cause", a."Date", a."Time" FROM "Record" AS o INNER JOIN "TimeRecord" AS a ON o."ID"=a."Record"
	ORDER BY a."Date" ASC, a."Time"`)
	if e != nil {
		elist = append(elist, "Select#Order#"+e.Error())
	}

	return elist
}

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

	_, e := stmt.Exec(m.Infa)
	if e != nil {
		return e
	}

	return nil
}

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

	rows, e := stmt.Query()
	if e != nil {
		return e
	}
	defer rows.Close()

	var infa string

	for rows.Next() {
		e = rows.Scan(&infa)
		if e != nil {
			return e
		}

		m.Rows = append(m.Rows, infa)
	}

	return nil
}
