package database

import (
	"context"
	"fmt"
	"sync"

	"git.yetaga.in/alazyreader/library/media"
)

type Memory struct {
	lock  sync.Mutex
	shelf []media.Book
}

func (m *Memory) GetAllBooks(_ context.Context) ([]media.Book, error) {
	m.lock.Lock()
	defer m.lock.Unlock()

	if m.shelf == nil {
		m.shelf = []media.Book{}
	}

	return m.shelf, nil
}

func (m *Memory) AddBook(_ context.Context, b *media.Book) error {
	m.lock.Lock()
	defer m.lock.Unlock()

	if m.shelf == nil {
		m.shelf = []media.Book{}
	}

	m.shelf = append(m.shelf, *b)
	return nil
}

func (m *Memory) UpdateBook(_ context.Context, old, new *media.Book) error {
	m.lock.Lock()
	defer m.lock.Unlock()

	if m.shelf == nil {
		m.shelf = []media.Book{}
		return fmt.Errorf("book does not exist")
	}

	if old.ID != new.ID {
		return fmt.Errorf("cannot change book ID")
	}

	for i := range m.shelf {
		if m.shelf[i].ID == old.ID {
			m.shelf[i] = *new
			return nil
		}
	}
	return fmt.Errorf("book does not exist")
}

func (m *Memory) DeleteBook(_ context.Context, b *media.Book) error {
	m.lock.Lock()
	defer m.lock.Unlock()

	if m.shelf == nil {
		m.shelf = []media.Book{}
		return fmt.Errorf("book does not exist")
	}

	for i := range m.shelf {
		if m.shelf[i].ID == b.ID {
			// reorder slice to remove book quickly
			m.shelf[i] = m.shelf[len(m.shelf)-1]
			m.shelf = m.shelf[:len(m.shelf)-1]
			return nil
		}
	}
	return fmt.Errorf("book does not exist")
}
