<?php

namespace App\Livewire\Projects\Tabs;

use App\Jobs\ProjectMosiacGeneratorJob;
use App\Models\Project;
use App\Models\ProjectMosaic;
use Carbon\Carbon;
use Livewire\Component;
use Livewire\WithPagination;

class Mosaic extends Component
{
    use WithPagination;

    public Project $project;

    public $formData = [
        'end_date' => '',
        'offset' => '7',
    ];
    public $showCreateModal = false;

    public $search = "";
    protected $listeners = [
        'Badge:refresh' => '$refresh',
    ];

    public function mount(Project $project)
    {
        $this->path = $project->download_path;
        $this->formData['end_date'] = Carbon::yesterday()->toDateString();
    }
    public function saveMosaic()
    {
        $this->validate([
            'formData.end_date' => ['required','date','before:today'],
            'formData.offset' => 'required|integer|min:1|max:1000',
        ]);

        $mosaic = $this->project->mosaics()->updateOrCreate([
            'name' => ProjectMosaic::projectMosaicNameFormat(new Carbon($this->formData['end_date']),(int) $this->formData['offset']),
            'offset' => $this->formData['offset'],
            'end_date' => $this->formData['end_date'],
        ], [
            'path' => $this->project->getMosaicPath(),
        ]);

        ProjectMosiacGeneratorJob::dispatch($mosaic);

        $this->showCreateModal = false;
    }

    public function openCreateMosiacsModal()
    {
        $this->showCreateModal = true;
    }

    public function getDateRangeProperty()
    {
        if (!$this->formData['end_date'] || !$this->formData['offset']) {
            return '<span class="text-red-500">Please give a correct date or offset</span>';
        }
        $start = (new Carbon($this->formData['end_date']))->subDays($this->formData['offset']-1);
        $end = new Carbon($this->formData['end_date']);
        return 'from '.$start->format('Y-m-d').' to '.$end->format('Y-m-d');
    }

    private function applySearch($query)
    {
        return $query->when($this->search !== '', function ($q){
            $q->where('name', 'like', '%'.$this->search.'%')
                ->orWhere('offset', 'like', '%' . $this->search . '%')
                ->orWhere('end_date', 'like', '%' . $this->search . '%');
        });
    }

    public function update($property)
    {
        if ($property === 'search') {
            $this->resetPage('mosaicPage');
        }
    }

    public function render()
    {
        $query = $this->project->mosaics()
            ->orderBy('offset', 'desc')
            ->orderBy('end_date', 'desc');
        $query = $this->applySearch($query);
        $mosaics = $query->paginate(10, pageName: 'mosaicPage');

        return view('livewire.projects.tabs.mosaic', [
            'mosaics' => $mosaics
        ]);
    }
}
