package main

import (
	// External
	werr "git.gibonuddevalla.se/go/wrappederror"
	"github.com/lib/pq"

	// 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 UpdateNotificationService(svc notification.Service) (created bool, err error) { // {{{
	if svc.Exists() {
		_, err = service.Db.Conn.Exec(
			`
			UPDATE public.notification
			SET
				prio=$2,
				configuration=$3
			WHERE
				prio=$1
			`,
			svc.GetPrio(),
			svc.Updated().GetPrio(),
			svc.Updated().JSON(),
		)
	} else {
		_, err = service.Db.Conn.Exec(
			`
			INSERT INTO public.notification(prio, configuration, service)
			VALUES($1, $2, $3)

			`,
			svc.Updated().GetPrio(),
			svc.Updated().JSON(),
			svc.GetType(),
		)
		created = true
	}

	if err != nil {
		// Check if this is just a duplicated prio, which isn't allowed.
		pgErr, isPgErr := err.(*pq.Error)
		if isPgErr && pgErr.Code == "23505" {
			return false, werr.New("Prio %d is already used by another service", svc.GetPrio())
		}

		return false, werr.Wrap(err).WithData(
			struct {
				Prio          int
				Configuration []byte
			}{
				svc.GetPrio(),
				svc.JSON(),
			},
		)
	}
	return
} // }}}
func DeleteNotificationService(prio int) (err error) { // {{{
	_, err = service.Db.Conn.Exec(
		`
		DELETE FROM public.notification
		WHERE
			prio = $1

		`,
		prio,
	)

	if err != nil {
		return werr.Wrap(err).WithData(struct{ Prio int }{prio})
	}
	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
} // }}}
