<?php

/**
 * @package         EngageBox
 * @version         6.3.8 Pro
 * 
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2020 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

namespace EngageBox;

defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Factory;

class OpeningSound
{
    protected $box = [];
    
    public function __construct($box = [])
    {
        $this->box = $box;
    }

    public function render()
    {
        $source = $this->box->params->get('opening_sound.source', '');
        
        if ($source === '')
        {
            return;
        }

        $ds = DIRECTORY_SEPARATOR;
        
        $url = '';

        switch ($source)
        {
            case 'file':
                $url = implode($ds, [rtrim(Uri::root(), $ds), $this->box->params->get('opening_sound.file', '')]);
                break;
            
            case 'url':
                $url = $this->box->params->get('opening_sound.url', '');
                break;
            
            default:
                $url = implode($ds, [rtrim(Uri::root(), $ds), 'media', 'com_rstbox', 'sound', $source . '.mp3']);
                break;
        }

        if (!$url)
        {
            return;
        }

        $this->attachOpeningSound($url, $this->box->id);
    }

    private function attachOpeningSound($url, $box_id)
    {
        $js = '
            <!-- EngageBox #' . $box_id . ' Actions Start -->
            !(function() { 
                if (!EngageBox) {
                    return;
                }

                EngageBox.onReady(function() {
                    var me = EngageBox.getInstance(' . $box_id . ');

                    if (!me) {
                        return;
                    }

                    me.on("open", function() {
                        const audio = new Audio("' . $url . '");
                        audio.pause();
                        audio.currentTime = 0;
                        audio.play();
                    });
                });
            })();
            <!-- EngageBox #' . $box_id . ' Actions End -->
        ';

        Factory::getDocument()->addScriptDeclaration($js);
    }
}