package main

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

	// Internal
	"smon/notification"

	// Standard
	"encoding/json"
)

type DbNotificationService struct {
	ID            int
	Service       string
	Configuration string
	Prio          int
}

func InitNotificationManager() (nm notification.Manager, err error) { // {{{
	var dbServices []DbNotificationService
	row := service.Db.Conn.QueryRow(`
		WITH services AS (
			SELECT
				id,
				prio,
				service,
				configuration::varchar
			FROM notification n
			ORDER BY
				prio ASC
		)
		SELECT COALESCE(jsonb_agg(s.*), '[]')
		FROM services s
		`,
	)
	var dbData []byte
	err = row.Scan(&dbData)
	if err != nil {
		err = werr.Wrap(err).WithCode("002-0006")
		return
	}

	err = json.Unmarshal(dbData, &dbServices)
	if err != nil {
		err = werr.Wrap(err).WithCode("002-0007")
		return
	}

	nm = notification.NewManager(logger)
	var service notification.Service
	for _, dbService := range dbServices {
		service, err = notification.ServiceFactory(
			dbService.Service,
			[]byte(dbService.Configuration),
			dbService.Prio,
			"blah",
			//config.Application.NotificationBaseURL,
			logger,
		)
		if err != nil {
			err = werr.Wrap(err).WithData(dbService.Service)
		}
		nm.AddService(service)
	}

	return
} // }}}

func AcknowledgeNotification(uuid string) (err error) { // {{{
	/*
	_, err = service.Db.Conn.Exec(`UPDATE schedule SET acknowledged=true WHERE schedule_uuid=$1`, uuid)
	if err != nil {
		err = werr.Wrap(err).WithData(uuid)
	}
	*/
	return
} // }}}
