<commit_before><?php
/**
 * This file is part of the EuradioNantes.eu package.
 *
 * (c) 2015 <NAME>
 * Made in Nantes, France - http://lespolypodes.com
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 *
 * File created by <EMAIL> (04/08/2015 - 17:07)
 */

namespace RadioSolution\ProgramBundle\Service\Tracks;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use ApaiIO\Configuration\GenericConfiguration;
use ApaiIO\Operations\Search;
use ApaiIO\ApaiIO;

/**
 * Class TrackRetriever
 * @url http://docs.aws.amazon.com/fr_fr/AWSECommerceService/latest/DG/ItemSearch.html
 * @package RadioSolution\ProgramBundle\Service\Tracks
 */
class TrackRetriever implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface|null
     */
    protected $container = null;

    /**
     * @var GenericConfiguration|null
     */
    protected $conf = null;

    /**
     * @var ApaiIO|null
     */
    protected $apaiIO = null;

    /**
     * @param ContainerInterface $container
     * @param string $locale
     * @param string $amazon_ws_api_key
     * @param string $amazon_ws_api_secret_key
     * @param string $amazon_ws_api_associate_tag
     */
    public function __construct(ContainerInterface $container, $locale,
        $amazon_ws_api_key, $amazon_ws_api_secret_key, $amazon_ws_api_associate_tag)
    {
        $this->setContainer($container);
        $this->conf = new GenericConfiguration();
        $this->conf
            ->setCountry($locale) // mind that we assume that Sf2 locale == Amazon locale
            ->setAccessKey($amazon_ws_api_key)
            ->setSecretKey($amazon_ws_api_secret_key)
            ->setAssociateTag($amazon_ws_api_associate_tag);
        $this->apaiIO = new ApaiIO($this->conf);
    }

    /**
     * @param ContainerInterface|NULL $container
     */
    public function setContainer(ContainerInterface $container = null)
    {
        if(empty($container)) {
            throw new \InvalidArgumentException(sprintf("container argument passed to %s cannot be null", __METHOD__));
        }
        $this->container = $container;
    }

    /**
     * @param string $terms
     *
     * @return array
     * @throws \Exception
     */
    public function search($terms = "")
    {
        if(empty($terms) || !is_string($terms)) {
            throw new \InvalidArgumentException(sprintf("terms argument passed to %s must be a string and cannot be null", __METHOD__));
        }
        list($artist, $title, $albumName) = $this->prepareItems($terms);
        $tracks = $album = $images = null;



        $search = new Search();
        $search
            ->setCategory('MP3Downloads')// DigitalMusic, MusicTracks, Music, MP3Downloads
            ->setCondition('All')// New (default) | Used | Collectible | Refurbished | All
            ->setRelationshipType('Tracks')
            ->setResponseGroup(array(
                'RelatedItems',
                'ItemAttributes',
                'Images',
            ))// Tracks won't work here
            ->setTitle($title)
            ->setKeywords(sprintf("%s %s %s", $artist, $albumName, $title));
        $xmlResponse = $this->apaiIO->runOperation($search);
        $xml         = new \SimpleXMLElement($xmlResponse);

        $result = isset($xml->Items->Item->ItemAttributes) ? $xml->Items->Item->ItemAttributes : null;
        $images = isset($xml->Items->Item->ImageSets) ? $xml->Items->Item->ImageSets : null;

        if(!$albumName) {
            if("Digital Music Album" === strval($xml->Items->Item->ItemAttributes->ProductGroup)) {
                $albumName = strval($xml->Items->Item->ItemAttributes->Title);
                $album =  $xml->Items->Item->ItemAttributes;
            }
            elseif("Parents" === strval($xml->Items->Item->RelatedItems->Relationship)) {
                $albumName = strval($xml->Items->Item->RelatedItems->RelatedItem->Item->ItemAttributes->Title);
                $album =  $xml->Items->Item->RelatedItems->RelatedItem->Item->ItemAttributes;
            }
        }
        // Tracks list search + second chance for albums images & details
        if (!$images || !$album || !$tracks ) {
            if($albumName) {
                $xml = $this->tracksSearch($artist, $albumName);
                if (isset($xml)) {
                    if (!$album && isset($xml->Items->Item->ItemAttributes)) {
                        $album = $xml->Items->Item->ItemAttributes;
                    }

                    if (!$images && isset($xml->Items->Item->ImageSets)) {
                        $images = $xml->Items->Item->ImageSets;
                    }
                    if (!$tracks) {
                        $tracks = $this->findTrackListInDiscography($xml, $title);
                    }

                    if (!$tracks && isset($xml->Items->Item->Tracks->Disc)) {
                        $tracks = $xml->Items->Item->Tracks->Disc->children();
                    }
                }
            }
        }

        //second chance
        // Tracks list search + second chance for albums images & details
        if (!$images || !$album || !$tracks) {
            if($albumName) {
            $xml = $this->tracksSearch($artist, $albumName, true);
            if (isset($xml)) {

                if (!$album && isset($xml->Items->Item->ItemAttributes)) {
                    $album = $xml->Items->Item->ItemAttributes;
                }

                if (!$images && isset($xml->Items->Item->ImageSets)) {
                    $images = $xml->Items->Item->ImageSets;
                }

                if (!$tracks) {
                    $tracks = $this->findTrackListInDiscography($xml, $title);
                }

                if (!$tracks && isset($xml->Items->Item->Tracks->Disc)) {
                    $tracks = $xml->Items->Item->Tracks->Disc->children();
                }
            }
            }
        }

        return array($album, $images, $tracks);
    }

    protected function findTrackListInDiscography($xml, $title)
    {
        $namespaces = $xml->getNamespaces();<commit_msg>trackSearcher, not used so far<commit_after><?php
/**
 * This file is part of the EuradioNantes.eu package.
 *
 * (c) 2015 <NAME>
 * Made in Nantes, France - http://lespolypodes.com
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 *
 * File created by <EMAIL> (04/08/2015 - 17:07)
 */

namespace RadioSolution\ProgramBundle\Service\Tracks;

use ApaiIO\Operations\Lookup;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use ApaiIO\Configuration\GenericConfiguration;
use ApaiIO\Operations\Search;
use ApaiIO\ApaiIO;

/**
 * Class TrackRetriever
 * @url http://docs.aws.amazon.com/fr_fr/AWSECommerceService/latest/DG/ItemSearch.html
 * @package RadioSolution\ProgramBundle\Service\Tracks
 */
class TrackRetriever implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface|null
     */
    protected $container = null;

    /**
     * @var GenericConfiguration|null
     */
    protected $conf = null;

    /**
     * @var ApaiIO|null
     */
    protected $apaiIO = null;

    /**
     * @param ContainerInterface $container
     * @param string $locale
     * @param string $amazon_ws_api_key
     * @param string $amazon_ws_api_secret_key
     * @param string $amazon_ws_api_associate_tag
     */
    public function __construct(ContainerInterface $container, $locale,
        $amazon_ws_api_key, $amazon_ws_api_secret_key, $amazon_ws_api_associate_tag)
    {
        $this->setContainer($container);
        $this->conf = new GenericConfiguration();
        $this->conf
            ->setCountry($locale) // mind that we assume that Sf2 locale == Amazon locale
            ->setAccessKey($amazon_ws_api_key)
            ->setSecretKey($amazon_ws_api_secret_key)
            ->setAssociateTag($amazon_ws_api_associate_tag);
        $this->apaiIO = new ApaiIO($this->conf);
    }

    /**
     * @param ContainerInterface|NULL $container
     */
    public function setContainer(ContainerInterface $container = null)
    {
        if(empty($container)) {
            throw new \InvalidArgumentException(sprintf("container argument passed to %s cannot be null", __METHOD__));
        }
        $this->container = $container;
    }

    /**
     * @param string $terms
     *
     * @return array
     * @throws \Exception
     */
    public function search($terms = "")
    {
        if(empty($terms) || !is_string($terms)) {
            throw new \InvalidArgumentException(sprintf("terms argument passed to %s must be a string and cannot be null", __METHOD__));
        }
        list($artist, $title, $albumName) = $this->prepareItems($terms);
        $tracks = $album = $images = null;



        $search = new Search();
        $search
            ->setCategory('MP3Downloads')// DigitalMusic, MusicTracks, Music, MP3Downloads
            ->setCondition('All')// New (default) | Used | Collectible | Refurbished | All
            ->setRelationshipType('Tracks')
            ->setResponseGroup(array(
                'RelatedItems',
                'ItemAttributes',
                'Images',
            ))// Tracks won't work here
            ->setTitle($title)
            ->setKeywords(sprintf("%s %s %s", $artist, $albumName, $title));
        $xmlResponse = $this->apaiIO->runOperation($search);
        $xml         = new \SimpleXMLElement($xmlResponse);

        $result = isset($xml->Items->Item->ItemAttributes) ? $xml->Items->Item->ItemAttributes : null;
        $images = isset($xml->Items->Item->ImageSets) ? $xml->Items->Item->ImageSets : null;

        if(!$albumName) {
            if("Digital Music Album" === strval($xml->Items->Item->ItemAttributes->ProductGroup)) {
                $albumName = strval($xml->Items->Item->ItemAttributes->Title);
                $album =  $xml->Items->Item->ItemAttributes;
            }
            elseif("Parents" === strval($xml->Items->Item->RelatedItems->Relationship)) {
                $albumName = strval($xml->Items->Item->RelatedItems->RelatedItem->Item->ItemAttributes->Title);
                $album =  $xml->Items->Item->RelatedItems->RelatedItem->Item->ItemAttributes;
            }
        }
        // Tracks list search + second chance for albums images & details
        if (!$images || !$album || !$tracks ) {
            if($albumName) {
                $xml = $this->tracksSearch($artist, $albumName);
                if (isset($xml)) {
                    if (!$album && isset($xml->Items->Item->ItemAttributes)) {
                        $album = $xml->Items->Item->ItemAttributes;
                    }

                    if (!$images && isset($xml->Items->Item->ImageSets)) {
                        $images = $xml->Items->Item->ImageSets;
                    }
                    if (!$tracks) {
                        $tracks = $this->findTrackListInDiscography($xml, $title);
                    }

                    if (!$tracks && isset($xml->Items->Item->Tracks->Disc)) {
                        $tracks = $xml->Items->Item->Tracks->Disc->children();
                    }
                }
            }
        }

        //second chance
        // Tracks list search + second chance for albums images & details
        if (!$images || !$album || !$tracks) {
            if($albumName) {
            $xml = $this->tracksSearch($artist, $albumName, true);
            if (isset($xml)) {

                if (!$album && isset($xml->Items->Item->ItemAttributes)) {
                    $album = $xml->Items->Item->ItemAttributes;
                }

                if (!$images && isset($xml->Items->Item->ImageSets)) {
                    $images = $xml->Items->Item->ImageSets;
                }

                if (!$tracks) {
                    $tracks = $this->findTrackListInDiscography($xml, $title);
                }

                if (!$tracks && isset($xml->Items->Item->Tracks->Disc)) {
                    $tracks = $xml->Items->Item->Tracks->Disc->children();
                }
            }
            }
        }

        return array($album, $images, $tracks);
    }

    public function findAlbumDetail($ASIN)
    {
        $search = new Lookup();
        $search
            ->setCondition('All')// New (default) | Used | Collectible | Refurbished | All
            ->setItemId($ASIN)
            ->setIdType("ASIN")
            ->setRelationshipType('Tracks')
            ->setResponseGroup(array(
                'RelatedItems',
                'Small',
            ))
        ;
        $xmlResponse = $this->apaiIO->runOperation($search);
        $xml         = new \SimpleXMLElement($xmlResponse);

        return $xml;
    }

    protected function findTrackListInDiscography($xml, $title)
    {
        $namespaces = $xml->getNamespaces();
{'fraction_non_alphanumeric': 0.13971826672791304, 'fraction_numerical': 0.0029092022661154496, 'mean_word_length': 2.048541423570595, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 226, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 70}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5325387', 'n_tokens_mistral': 3701, 'n_tokens_neox': 3534, 'n_words': 700}