<?php

namespace Blazemedia\Affiliation\Rendering\LinkParser;

class LinkParser {

    const PROGRAMS_TO_PARSE = [
        'Amazon',
        'Ebay',
        'AmazonShorted', 
        'EbayShorted', 
        'Awin', 
        'PrettyLink',
        'TradeTracker', 
        'Partnerize',
        'PrimeVideo'
    ];

    protected $content;
    protected $programs;

    /**
     * Individua i link nel testo e li estrae tutti 
     *
     * @param string $content
     * @return array
     */
    public function parse( string $content, callable $callback = null ) {

        $programs = $this->getPrograms( $content );
        
        return array_reduce( $programs, fn( $programs, $program ) => [ ...$programs, ...$program->links ], [] );

    }


    /**
     * scansiona ogni tipologia di link da sostituire e recupera i pattern che trova nel contenuto 
     *
     * @param [type] $content
     * @return array
     */
    protected function getPrograms( string $content ) {

        $ns = 'Blazemedia\\Affiliation\\Rendering\\LinkParser\\Patterns\\';
        
        return array_filter( 

            array_map( fn( $patternClass ) => new ( $ns . $patternClass )( $content ), self::PROGRAMS_TO_PARSE ),

            fn( $pattern ) => !empty($pattern->links) 
        );
    }
    

}
