<?php
class Downloader
{
    private static $loggedIn = false;

    public function __construct()
    {
        if( !self::$loggedIn )
        {
            $this->login();
        }
    }

    private function login( ): void
    {
        echo "[LOGIN] Logging in...";
        $ch = curl_init();

        curl_setopt( $ch, CURLOPT_URL, "http://usdb.animux.de/index.php?&link=home" );
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_COOKIEFILE, DOWNLOAD_PATH . '/cookies.txt' );
        curl_setopt( $ch, CURLOPT_COOKIEJAR, DOWNLOAD_PATH . '/cookies.txt' );
        // In real life you should use something like:
        curl_setopt( $ch, CURLOPT_POSTFIELDS,
            http_build_query(
                array(
                    'user' => ANIMUX_USERNAME,
                    'userpass3' => ANIMUX_PASSWORD
                ) ) );

        // Receive server response ...
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );



        curl_close( $ch );
        self::$loggedIn = true;
        echo "OK\n";
    }

    /**
     * @param int $a_id
     *
     * @return bool
     *
     * @throws Exception
     */
    public function requestSong( int $a_id ): bool
    {
        if( ( $out = $this->downloadFile( $a_id ) ) === false )
        {
            return false;
        }
        $this->saveFile( $out );
        return true;
    }

    /**
     * @param $a_file_id
     *
     * @return bool|string
     */
    private function downloadFile( $a_file_id )
    {
        echo "[INFO] Requesting file id $a_file_id...";
        $ch = curl_init();

        curl_setopt( $ch, CURLOPT_URL, "http://usdb.animux.de/index.php?link=gettxt&id=$a_file_id" );
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_COOKIEFILE, DOWNLOAD_PATH . '/cookies.txt' );
        curl_setopt( $ch, CURLOPT_COOKIEJAR, DOWNLOAD_PATH . '/cookies.txt' );
        // In real life you should use something like:
        curl_setopt( $ch, CURLOPT_POSTFIELDS,
            http_build_query(
                array(
                    'wd' => 1,
                ) ) );

        // Receive server response ...
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

        $out = curl_exec( $ch );

        if( strpos( $out, 'Datensatz nicht gefunden' ) !== false )
        {
            echo "Not found - Skip\n";
            curl_close( $ch );
            return false;
        }
        curl_close( $ch );
        echo "OK\n";

        return utf8_decode( $out );

    }


    /**
     * @param $a_input
     *
     * @return bool
     * @throws Exception
     */
    private function saveFile( $a_input ): bool
    {


        $out = strpos( $a_input, '<textarea' ) + 37;
        if( $out === false )
        {
            return false;
        }
        $_to = strpos( $a_input, '</textarea>' );
        $out = substr( $a_input, $out, $_to - $out );


        $artist = str_replace( array( '#ARTIST:', '/' ), array( '', '-' ), strtok( $out, "\n" ) );
	$artist = utf8_encode( $artist );
	$artist = str_replace( array( "ö", "ä", "ü" ), array( "oe", "ae", "ue" ), $artist );
	$artist = preg_replace( '/[^a-zA-Z0-9\ \-]/', '', $artist );

        $title = str_replace( array( '#TITLE:', '/' ), array( '', '-' ), strtok( "\n" ) );
	$title = utf8_encode( $title );
	$title = str_replace( array( "ö", "ä", "ü" ), array( "oe", "ae", "ue" ), $title );
	$title = preg_replace( '/[^a-zA-Z0-9\ \-]/', '', $title );


        echo "[INFO] Found $artist - $title\n";
        if( is_dir( DOWNLOAD_PATH . '/' . $artist . '/' ) === false )
        {
            echo "[INFO] Creating Artist-Directory...";
            if ( !mkdir( $concurrentDirectory = DOWNLOAD_PATH . '/' . $artist . '/' ) && !is_dir( $concurrentDirectory ) )
            {
                throw new Exception( 'Cannot create the directory for the Artist' );
            }
            echo "OK";
        }
        else
        {
            echo "[INFO] Artist-Directory exists\n";

        }
        if( file_exists( DOWNLOAD_PATH . '/' . $artist . '/' . $artist . ' - ' . $title . '.txt' ) === true )
        {
            echo "[INFO] Already downloaded - Skip\n";

            return false;
        }
        if( ( $file = fopen( DOWNLOAD_PATH . "/$artist/$artist - $title.txt", 'wb+' ) ) === false )
        {
            throw new RuntimeException( "$artist - $title *** Cannot open file handler" );
        }

        if ( fwrite( $file, $out ) === false )
        {
            throw new RuntimeException( "$artist - $title *** Cannot write to file" );
        }
        fclose( $file );

        echo "\n[SUCCESS] Downloaded \"$title - $artist\"\n";
        return true;
    }



}