<?php

namespace App\AlbumSources;

use App\Photo;
use App\Storage;
use OpenCloud\Rackspace;

class RackspaceSource extends OpenStackSource
{
    protected function getClient()
    {
        $endpoint = Rackspace::US_IDENTITY_ENDPOINT;

        if ($this->configuration->service_region == 'LON')
        {
            $endpoint = Rackspace::UK_IDENTITY_ENDPOINT;
        }

        return new Rackspace($endpoint, [
            'username' => $this->configuration->username,
            'apiKey' => decrypt($this->configuration->password)
        ]);
    }

    /**
     * Gets the name of this album source.
     * @return string
     */
    public function getName()
    {
        return 'global.album_sources.rackspace';
    }

    /**
     * Gets the absolute URL to the given photo file.
     * @param Photo $photo Photo to get the URL to.
     * @param string $thumbnail Thumbnail to get the image to.
     * @return string
     */
    public function getUrlToPhoto(Photo $photo, $thumbnail = null)
    {
        $isCdnEnabled = false;
        $cdnService = $this->getStorageService()->getCdnService();
        $thisCdnContainer = null;

        foreach ($cdnService->listContainers() as $cdnContainer)
        {
            if ($cdnContainer->name == $this->configuration->container_name)
            {
                $isCdnEnabled = true;
                $thisCdnContainer = $cdnContainer;
            }
        }

        if ($isCdnEnabled)
        {
            return sprintf('%s/%s', $thisCdnContainer->getCdnSslUri(), $this->getPathToPhoto($photo, $thumbnail));
        }

        return parent::getPathToPhoto($photo, $thumbnail);
    }
}