<?php

namespace App\Models;

use App\Events\ProjectMosaicStatus;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ProjectMosaic extends Model
{
    use HasFactory;
    use \App\Traits\HasStatus;

    protected $casts = [
        'end_date' => 'datetime',
    ];

    protected $fillable = [
        'name',
        'path',
        'week',
        'year',
        'end_date',
        'offset',
        'status'
    ];


    public static function getFilenameByPeriod(Carbon $endDate, int $offset)
    {
        return sprintf('%s.tif', strtolower(self::projectMosaicNameFormat($endDate, $offset)));
    }

    public static function projectMosaicNameFormat(Carbon $endDate, int $offset): string
    {

        $paddedWeek = str_pad($endDate->clone()->subDays($offset)->week, 2, '0', STR_PAD_LEFT);

        return sprintf('Week_%s_%s',
            $paddedWeek,
            $endDate->clone()->subDays($offset)->year
        );
    }

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function getStartDateAttribute()
    {
        return $this->end_date->subDay($this->offset);
    }

    protected static function booted(): void
    {
        parent::booted();
        static::updated(function (ProjectMosaic $projectMosaic) {
            event(new ProjectMosaicStatus($projectMosaic));
        });
    }

}
