<?php

namespace App\Components;

use App\Interface\NoteOwner;
use App\Models\Note;
use App\Services\NoteService;
use Livewire\Component;
use Livewire\WithPagination;

class NoteManager extends Component {
    use WithPagination;

    public NoteOwner $owner;
    public bool $show = false;
    public string $note = '';
    public $perPage = 10;
    public bool $primary = false;

    protected $paginationTheme = 'bootstrap';

    public function mount(NoteOwner $owner) {
        $this->owner = $owner;
        $this->show = false;
    }

    public function showAddNote() {
        $this->show = true;
    }

    public function addNote(NoteService $noteService) {
        $data = $this->validate([
            'note' => 'required|string|min:1'
        ]);

        $noteService->addNote($this->owner, $data['note'], $this->primary);

        $this->resetPage();
        $this->hideAddNote();
    }

    public function hideAddNote() {
        $this->show = false;
        $this->reset('note');
    }

    public function deleteNote(NoteService $noteService, int $id) {
        $note = Note::findOrFail($id);

        $noteService->deleteNote($note);

        $this->resetPage();
    }

    public function render() {
        $builder = $this->primary ? $this->owner->keyInfo() : $this->owner->notes()->where('is_primary', false);
        return view('components.note-manager', [
            'notes' => $builder
                ->paginate($this->perPage),
        ]);
    }
}
