package monitor

import (
	"fmt"
	"local/rssmon3/config"
	"local/storage"
	"log"

	"github.com/golang-collections/go-datastructures/queue"
)

const nsQueued = "nsQueued"

type Queue struct {
	queue *queue.PriorityQueue
}

func newQueue() (*Queue, error) {
	q := queue.NewPriorityQueue(1)
	db := config.Values().DB
	keys, err := db.List([]string{nsQueued})
	if err == storage.ErrNotFound {
		keys = []string{}
	} else if err != nil {
		return nil, err
	}
	for _, key := range keys {
		b, err := db.Get(key, nsQueued)
		if err != nil {
			return nil, fmt.Errorf("failed to get %s:%s: %v", nsQueued, key, err)
		}
		i := &Item{}
		if err := i.Decode(b); err != nil {
			return nil, err
		}
		q.Put(i)
	}
	return &Queue{
		queue: q,
	}, nil
}

func (q *Queue) Push(i *Item) {
	if i == nil {
		return
	}
	q.queue.Put(i)
	b, err := i.Encode()
	if err != nil {
		log.Println("[Push]", err)
		return
	}
	if err := config.Values().DB.Set(i.Key, b, nsQueued); err != nil {
		log.Println("[Push]", err)
		return
	}
}

func (q *Queue) Pop() *Item {
	is, err := q.queue.Get(1)
	if err != nil {
		return nil
	}
	if len(is) < 1 {
		return nil
	}
	if is[0] == nil {
		return nil
	}
	return is[0].(*Item)
}

func (q *Queue) Peek() *Item {
	i := q.queue.Peek()
	if i == nil {
		return nil
	}
	return i.(*Item)
}

func (q *Queue) Len() int {
	return q.queue.Len()
}
