<?php
/**
 * the Import Module just iterates
 */
ini_set('exif.encode_unicode', 'UTF-8');

use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Cached\CachedAdapter;
use League\Flysystem\Cached\Storage\Memory as MemoryStore;
use League\Flysystem\Filesystem;

$client = new S3Client($config['minio'][0]);

$s3adapter = new AwsS3Adapter($client, 'photos', '', ['StorageClass' => 'REDUCED_REDUNDANCY']);
$cacheStore = new MemoryStore();
$adapter = new CachedAdapter($s3adapter, $cacheStore);
$filesystem = new Filesystem($adapter);

$contents = $filesystem->listContents('/', true);
foreach ($contents as $object) {
    if (stristr($object['path'], 'dark')) {
        if ($object['type'] == "file") {

            $photoBean = R::findOne('photo', 'basename = ? AND path = ?', [$object['basename'], $object['path']]);
            if (is_null($photoBean)) {
                $photoBean = R::dispense('photo');
                $photoBean->basename = $object['basename'];
                $photoBean->path = $object['path'];
            }

            $stream = $filesystem->readStream($object['path']);
            $content = "";
            $startFound = false;
            while (!$startFound && !feof($stream)) {
                $content .= stream_get_contents($stream, 128);
                $offset = strpos($content, '<x:xmpmeta');
                if ($offset != false) {
                    $startFound = true;
                }
            }

            // jump to the found offset
            $content = stream_get_contents($stream, 128, $offset);

            $endFound = false;
            while (!$endFound && !feof($stream)) {
                $content .= stream_get_contents($stream, 128);
                $offset = strpos($content, '</x:xmpmeta>');
                if ($offset != false) {
                    $endFound = true;
                }
            }

            fclose($stream);

            $document = new DOMDocument();
            $document->loadXml($content);
            $xpath = new DOMXpath($document);

            /**
             * most likely a bit hackish.. thats how I do get all namespaces...
             */
            $results = preg_match_all('_xmlns:([A-Za-z]+)="(.*)"_U', $content, $matches);
            foreach ($matches[1] as $key => $alias) {
                // echo "registering $alias for ".$matches[2][$key]."\n";
                $xpath->registerNamespace($alias, $matches[2][$key]);
            }
            $elements = $xpath->query("//*[name()='dc:subject']//rdf:li");
            $tags = [];
            if (!is_null($elements)) {
                foreach ($elements as $element) {
                    $value = trim($element->nodeValue);
                    if (!empty($value)) {
                        $tags[] = strtolower($value);
                    }
                }
            }
            $beanTags = R::tag($photoBean);
            if ((count($beanTags) > 0) && count($tags) > 0) {
                // the bean has already tags connected to it.
                // add new tags
                $newTags = array_diff($tags, $beanTags);
                if (count($newTags) > 0) {
                    foreach ($newTags as $tag) {
                        R::addTags($photoBean, [$tag]);
                    }
                }
                // and remove old tags
                $deleteTags = array_diff($beanTags, $tags);
                if (count($deleteTags) > 0) {
                    foreach ($deleteTags as $tag) {
                        R::untag($photoBean, [$tag]);
                    }
                }
            } elseif (count($tags) > 0) {
                // new bean - just add all tags.
                R::addTags($photoBean, $tags);
            } else {
                if (count($beanTags) > 0) {
                    // old bean with tags attached though the pic does not have
                    // any tags anymore. remove them
                    foreach ($beanTags as $tag) {
                        R::untag($photoBean, [$tag]);
                    }
                }
            }

            // finally, store the bean and it's tags.
            R::store($photoBean);
        }
    }
}