<commit_before><?php

namespace CultuurNet\UDB3\UDB2\Media;

use Broadway\Domain\DomainMessage;
use CultureFeed_Cdb_Data_EventDetail;
use CultureFeed_Cdb_Data_Media;
use CultureFeed_Cdb_Item_Base;
use CultureFeed_Cdb_Data_File;
use CultuurNet\UDB3\Media\Image;
use CultuurNet\UDB3\Offer\Events\Image\AbstractImageAdded;
use CultuurNet\UDB3\Offer\Events\Image\AbstractImageRemoved;
use CultuurNet\UDB3\Offer\Events\Image\AbstractImageUpdated;
use CultuurNet\UDB3\Offer\Events\Image\AbstractMainImageSelected;
use ValueObjects\Identity\UUID;
use ValueObjects\String\String as StringLiteral;

trait EditImageTrait
{
    protected $imageTypes = [
        CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO,
        CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB
    ];

    /**
     * Delete a given index on the cdb item.
     *
     * @param CultureFeed_Cdb_Item_Base $cdbItem
     * @param Image $image
     */
    protected function removeImageFromCdbItem(
        CultureFeed_Cdb_Item_Base $cdbItem,
        Image $image
    ) {
        $oldMedia = $this->getCdbItemMedia($cdbItem);

        $newMedia = new CultureFeed_Cdb_Data_Media();
        foreach ($oldMedia as $key => $file) {
            if (!$this->fileMatchesMediaObject($file, $image->getMediaObjectId())) {
                $newMedia->add($file);
            }
        }

        $images = $newMedia->byMediaTypes($this->imageTypes);
        if ($images->count() > 0) {
            $images->rewind();
            $images->current()->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
        }

        $details = $cdbItem->getDetails();
        $details->rewind();
        $details->current()->setMedia($newMedia);
    }

    /**
     * Select the main image for a cdb item.
     *
     * @param CultureFeed_Cdb_Item_Base $cdbItem
     * @param Image $image
     */
    protected function selectCdbItemMainImage(
        CultureFeed_Cdb_Item_Base $cdbItem,
        Image $image
    ) {
        $media = $this->getCdbItemMedia($cdbItem);
        $mainImageId = $image->getMediaObjectId();

        $mainImages = $media->byMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
        if ($mainImages->count() > 0) {
            $mainImages->rewind();
            $mainImages->current()->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB);
        }

        foreach ($media as $file) {
            if ($this->fileMatchesMediaObject($file, $mainImageId)) {
                $file->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
            }
        }
    }

    /**
     * Update an existing image on the cdb item.
     *
     * @param \CultureFeed_Cdb_Item_Base $cdbItem
     * @param UUID $mediaObjectId
     * @param StringLiteral $description
     * @param StringLiteral $copyrightHolder
     */
    protected function updateImageOnCdbItem(
        CultureFeed_Cdb_Item_Base $cdbItem,
        UUID $mediaObjectId,
        StringLiteral $description,
        StringLiteral $copyrightHolder
    ) {
        $media = $this->getCdbItemMedia($cdbItem);

        foreach ($media as $file) {
            if ($this->fileMatchesMediaObject($file, $mediaObjectId)) {
                $file->setTitle((string) $description);
                $file->setCopyright((string) $copyrightHolder);
            }
        }
    }


    /**
     * Add an image to the cdb item.
     *
     * @param CultureFeed_Cdb_Item_Base $cdbItem
     * @param Image $image
     */
    protected function addImageToCdbItem(
        CultureFeed_Cdb_Item_Base $cdbItem,
        Image $image
    ) {
        $sourceUri = (string) $image->getSourceLocation();
        $uriParts = explode('/', $sourceUri);
        $media = $this->getCdbItemMedia($cdbItem);

        $file = new CultureFeed_Cdb_Data_File();
        $file->setMain();
        $file->setHLink($sourceUri);

        // If there are no existing images the newly added one should be main.
        if ($media->byMediaTypes($this->imageTypes)->count() === 0) {
            $file->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
        } else {
            $file->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB);
        }

        $filename = end($uriParts);
        $fileparts = explode('.', $filename);
        $extension = strtolower(end($fileparts));
        if ($extension === 'jpg') {
            $extension = 'jpeg';
        }

        $file->setFileType($extension);
        $file->setFileName($filename);

        $file->setCopyright((string) $image->getCopyrightHolder());
        $file->setTitle((string) $image->getDescription());

        $media->add($file);
    }

    /**
     * Get the media for a CDB item.
     *
     * If the items does not have any detials, one will be created.
     *
     * @param \CultureFeed_Cdb_Item_Base $cdbItem
     *
     * @return CultureFeed_Cdb_Data_Media
     */
    protected function getCdbItemMedia(CultureFeed_Cdb_Item_Base $cdbItem)
    {
        $details = $cdbItem->getDetails();
        $details->rewind();

        // Get the first detail.<commit_msg>III-459: Fall back to jpeg if the image source location URL does not contain a file extension<commit_after><?php

namespace CultuurNet\UDB3\UDB2\Media;

use Broadway\Domain\DomainMessage;
use CultureFeed_Cdb_Data_EventDetail;
use CultureFeed_Cdb_Data_Media;
use CultureFeed_Cdb_Item_Base;
use CultureFeed_Cdb_Data_File;
use CultuurNet\UDB3\Media\Image;
use CultuurNet\UDB3\Offer\Events\Image\AbstractImageAdded;
use CultuurNet\UDB3\Offer\Events\Image\AbstractImageRemoved;
use CultuurNet\UDB3\Offer\Events\Image\AbstractImageUpdated;
use CultuurNet\UDB3\Offer\Events\Image\AbstractMainImageSelected;
use ValueObjects\Identity\UUID;
use ValueObjects\String\String as StringLiteral;

trait EditImageTrait
{
    protected $imageTypes = [
        CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO,
        CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB
    ];

    /**
     * Delete a given index on the cdb item.
     *
     * @param CultureFeed_Cdb_Item_Base $cdbItem
     * @param Image $image
     */
    protected function removeImageFromCdbItem(
        CultureFeed_Cdb_Item_Base $cdbItem,
        Image $image
    ) {
        $oldMedia = $this->getCdbItemMedia($cdbItem);

        $newMedia = new CultureFeed_Cdb_Data_Media();
        foreach ($oldMedia as $key => $file) {
            if (!$this->fileMatchesMediaObject($file, $image->getMediaObjectId())) {
                $newMedia->add($file);
            }
        }

        $images = $newMedia->byMediaTypes($this->imageTypes);
        if ($images->count() > 0) {
            $images->rewind();
            $images->current()->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
        }

        $details = $cdbItem->getDetails();
        $details->rewind();
        $details->current()->setMedia($newMedia);
    }

    /**
     * Select the main image for a cdb item.
     *
     * @param CultureFeed_Cdb_Item_Base $cdbItem
     * @param Image $image
     */
    protected function selectCdbItemMainImage(
        CultureFeed_Cdb_Item_Base $cdbItem,
        Image $image
    ) {
        $media = $this->getCdbItemMedia($cdbItem);
        $mainImageId = $image->getMediaObjectId();

        $mainImages = $media->byMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
        if ($mainImages->count() > 0) {
            $mainImages->rewind();
            $mainImages->current()->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB);
        }

        foreach ($media as $file) {
            if ($this->fileMatchesMediaObject($file, $mainImageId)) {
                $file->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
            }
        }
    }

    /**
     * Update an existing image on the cdb item.
     *
     * @param \CultureFeed_Cdb_Item_Base $cdbItem
     * @param UUID $mediaObjectId
     * @param StringLiteral $description
     * @param StringLiteral $copyrightHolder
     */
    protected function updateImageOnCdbItem(
        CultureFeed_Cdb_Item_Base $cdbItem,
        UUID $mediaObjectId,
        StringLiteral $description,
        StringLiteral $copyrightHolder
    ) {
        $media = $this->getCdbItemMedia($cdbItem);

        foreach ($media as $file) {
            if ($this->fileMatchesMediaObject($file, $mediaObjectId)) {
                $file->setTitle((string) $description);
                $file->setCopyright((string) $copyrightHolder);
            }
        }
    }


    /**
     * Add an image to the cdb item.
     *
     * @param CultureFeed_Cdb_Item_Base $cdbItem
     * @param Image $image
     */
    protected function addImageToCdbItem(
        CultureFeed_Cdb_Item_Base $cdbItem,
        Image $image
    ) {
        $sourceUri = (string) $image->getSourceLocation();
        $uriParts = explode('/', $sourceUri);
        $media = $this->getCdbItemMedia($cdbItem);

        $file = new CultureFeed_Cdb_Data_File();
        $file->setMain();
        $file->setHLink($sourceUri);

        // If there are no existing images the newly added one should be main.
        if ($media->byMediaTypes($this->imageTypes)->count() === 0) {
            $file->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_PHOTO);
        } else {
            $file->setMediaType(CultureFeed_Cdb_Data_File::MEDIA_TYPE_IMAGEWEB);
        }

        // If the file name does not contain an extension, default to jpeg.
        $extension = 'jpeg';

        // If the file name does contain an extension, then normalize it.
        $filename = end($uriParts);
        if (false !== strpos($filename, '.')) {
            $fileparts = explode('.', $filename);
            $extension = strtolower(end($fileparts));
            if ($extension === 'jpg') {
                $extension = 'jpeg';
            }
        }

        $file->setFileType($extension);
        $file->setFileName($filename);

        $file->setCopyright((string) $image->getCopyrightHolder());
        $file->setTitle((string) $image->getDescription());

        $media->add($file);
    }

    /**
     * Get the media for a CDB item.
     *
     * If the items does not have any detials, one will be created.
     *
     * @param \CultureFeed_Cdb_Item_Base $cdbItem
     *
     * @return CultureFeed_Cdb_Data_Media
     */
    protected function getCdbItemMedia(CultureFeed_Cdb_Item_Base $cdbItem)
    {
        $details = $cdbItem->getDetails();
        $details->rewind();

        // Get the first detail.
{'fraction_non_alphanumeric': 0.11902934970266642, 'fraction_numerical': 0.0022060234030308844, 'mean_word_length': 2.601727115716753, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 99, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4984152', 'n_tokens_mistral': 3252, 'n_tokens_neox': 3195, 'n_words': 585}