<?php

declare(strict_types=1);

namespace External\PompoBundle\DataGo\Util;

use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use KupShop\CatalogBundle\Product\ProductFinder;

class PhotoUpdater
{
    private DataGoApi $dataGoApi;
    private PhotoDownloader $photoDownloader;
    private ProductFinder $productFinder;

    public function __construct(DataGoApi $dataGoApi, PhotoDownloader $photoDownloader, ProductFinder $productFinder)
    {
        $this->dataGoApi = $dataGoApi;
        $this->photoDownloader = $photoDownloader;
        $this->productFinder = $productFinder;
    }

    public function updatePhotosLatestChanges(bool $force = false): void
    {
        $dbcfg = \Settings::getDefault();
        $pompo = $dbcfg->loadValue('pompo');

        $hours = 6;
        $startTimestamp = time();

        // get timestamp of last run
        if ($timestamp = ($pompo['photosUpdate']['timestamp'] ?? null)) {
            $now = (new \DateTime());
            $date = (new \DateTime())->setTimestamp($timestamp);

            $diff = $date->diff($now);
            $hours = $diff->h;
        }

        if ($hours <= 0 && $force) {
            $hours = 1;
        }

        if ($hours > 0) {
            $this->updatePhotosByChanges($hours);
            // update timestamp of lat run
            $pompo['photosUpdate']['timestamp'] = $startTimestamp;
            $dbcfg->saveValue('pompo', $pompo, false);
        }
    }

    public function updatePhotosByChanges(int $hours = 12): void
    {
        // load codes of products where was detected some change in images
        foreach ($this->dataGoApi->getProductPhotosChanges($hours) as $productCode) {
            if (!($productId = $this->productFinder->getProductIdByCode($productCode))) {
                continue;
            }

            $this->updatePhotos($productId, $productCode);
        }
    }

    public function updatePhotos(int $productId, string $code): void
    {
        // load remote photos by product code
        foreach ($this->dataGoApi->getProductPhotos($code) as $position => $photo) {
            if ($photoId = $this->photoDownloader->updatePhoto($photo)) {
                try {
                    sqlQueryBuilder()
                        ->insert('photos_products_relation')
                        ->directValues([
                            'id_photo' => $photoId,
                            'id_product' => $productId,
                            'show_in_lead' => $position == 0 ? 'Y' : 'N',
                            'date_added' => (new \DateTime())->format('Y-m-d H:i:s'),
                            'position' => $position,
                        ])
                        ->execute();
                } catch (UniqueConstraintViolationException $e) {
                }

                // clear photo thumbnails
                $this->clearPhotoThumbnails($photoId);
            }
        }
    }

    private function clearPhotoThumbnails(int $photoId): void
    {
        $photo = new \Photos();
        $photo->newImage($photoId);
        $photo->clearThumbnails();
    }
}
