package main

import (
	// External
	werr "git.gibonuddevalla.se/go/wrappederror"

	// Standard
	"sort"
)

type Section struct {
	ID     int
	Name   string
	AreaID int `db:"area_id"`
	Area   Area

	Triggers []Trigger
}

func (s *Section) SortedTriggers() []Trigger {
	sort.SliceStable(s.Triggers, func(i, j int) bool {
		return s.Triggers[i].Name < s.Triggers[j].Name
	})

	return s.Triggers
}

func SectionCreate(areaID int, name string) (err error) { // {{{
	_, err = service.Db.Conn.Exec(`INSERT INTO section(area_id, name) VALUES($1, $2)`, areaID, name)
	return
} // }}}
func SectionRename(id int, name string) (err error) { // {{{
	_, err = service.Db.Conn.Exec(`UPDATE section SET name=$2 WHERE id=$1`, id, name)
	return
} // }}}
func SectionDelete(id int) (err error) { // {{{
	_, err = service.Db.Conn.Exec(`DELETE FROM public.trigger WHERE section_id = $1`, id)
	if err != nil {
		return werr.Wrap(err).WithData(id)
	}

	_, err = service.Db.Conn.Exec(`DELETE FROM public.section WHERE id = $1`, id)
	if err != nil {
		return werr.Wrap(err).WithData(id)
	}
	return
} // }}}
