<?php

namespace App\Imports;

use App\Models\Group;
use Carbon\Carbon;
use App\Models\Import;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeImport;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class ImportsImport implements OnEachRow, WithStartRow, WithMultipleSheets, WithEvents, WithChunkReading, ShouldQueue
{
    public $id;
    public $group;
    public $locale;

    public function __construct(int $id, Group $group, string $locale)
    {
        $this->id = $id;
        $this->group = $group->id;
        $this->locale = $locale;
    }

    public function sheets(): array
    {
        return [
            0 => $this,
        ];
    }

    public function startRow(): int
    {
        return 10;
    }

    public function chunkSize(): int
    {
        return 1000;
    }

    public function registerEvents(): array
    {
        return [
            BeforeImport::class => function (BeforeImport $event) {
                $totalRows = $event->getReader()->getTotalRows();

                if (filled($totalRows)) {
                    cache()->forever("total_rows_{$this->id}", array_values($totalRows)[0]);
                    cache()->forever("start_date_{$this->id}", now()->unix());
                }
            },
            AfterImport::class => function (AfterImport $event) {
                cache(["end_date_{$this->id}" => now()], now()->addMinute());
                cache()->forget("total_rows_{$this->id}");
                cache()->forget("start_date_{$this->id}");
                cache()->forget("current_row_{$this->id}");
            },
        ];
    }

    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function onRow(Row $row)
    {
        $rowIndex = $row->getIndex();
        $row      = array_map('trim', $row->toArray());
        $date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[1]);
        cache()->forever("current_row_{$this->id}", $rowIndex);
        // sleep(0.1);
        $row['group'] = $this->group;
        $row['locale'] = $this->locale;

        try {
            Import::create([
                'locale' => $row['locale'],
                'group_id' => $row['group'],
                'title'  => $row[2],
                'country'  => $row[3],
                'unit'  => $row[4],
                'price'  => $row[5],
                'currency' => $row[6],
                'registered_at' => Carbon::createFromInterface($date),
            ]);
        } catch (\Throwable $th) {
            info($th->getMessage());
            // dd($row);
        }
    }
}
