package queue

import (
	"encoding/json"
	"fmt"
	"os"
	"time"
)

type QueueElement struct {
	Value       string    `json:"value"`
	EnqueueTime time.Time `json:"enqueue_time"`
	MinDuration int       `json:"min_duration"` // Minimum duration in seconds
}

type Queue struct {
	Elements []QueueElement
	FilePath string
}

func NewQueue(filePath string) (*Queue, error) {
	q := &Queue{
		Elements: make([]QueueElement, 0),
		FilePath: filePath,
	}

	// Load state from file
	if _, err := os.Stat(filePath); err == nil {
		data, err := os.ReadFile(filePath)
		if err != nil {
			return nil, fmt.Errorf("error reading state file: %w", err)
		}
		if err := json.Unmarshal(data, &q.Elements); err != nil {
			return nil, fmt.Errorf("error parsing state file: %w", err)
		}
	}
	return q, nil
}

func (q *Queue) Enqueue(element string, minDuration int) {
	q.Elements = append(q.Elements, QueueElement{
		Value:       element,
		EnqueueTime: time.Now(),
		MinDuration: minDuration,
	})
}

func (q *Queue) Dequeue() (string, error) {
	if len(q.Elements) == 0 {
		return "", fmt.Errorf("queue is empty")
	}

	currentTime := time.Now()
	for i, elem := range q.Elements {
		// Check if the element has satisfied its minimum duration in the queue
		if currentTime.Sub(elem.EnqueueTime).Seconds() >= float64(elem.MinDuration) {
			// Remove the element from the queue
			q.Elements = append(q.Elements[:i], q.Elements[i+1:]...)
			return elem.Value, nil
		}
	}

	return "", fmt.Errorf("no elements are ready for dequeuing")
}

func (q *Queue) Save() error {
	data, err := json.Marshal(q.Elements)
	if err != nil {
		return fmt.Errorf("error serializing state: %w", err)
	}
	if err := os.WriteFile(q.FilePath, data, 0644); err != nil {
		return fmt.Errorf("error writing state to file: %w", err)
	}
	return nil
}