<?php
	if ( ! defined( 'ABSPATH' ) ) exit;

    class DigitalSignage4_DisplayedVideoProduct
    {
        public static function getDisplayedVideoProduct($idProduct)
        {
            self::setDefaultDatabaseOption();
            $option = DigitalSignage4_caller::getInstance()->get_data(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT);
            if (isset($option[$idProduct])) {
                return $option[$idProduct];
            }
            throw new Exception("Not found");
        }

        public static function setDisplayedVideoProduct($idProduct, $idVideo)
        {
            self::setDefaultDatabaseOption();
            $option = DigitalSignage4_caller::getInstance()->get_data(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT);
            $option[$idProduct] = $idVideo;
            DigitalSignage4_caller::getInstance()->save_data(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT, $option);
        }

        // Si une vidéo est supprimée, et est la vidéo affichée pour un produit, on change cette vidéo par la derniere crée
        public static function removeDisplayedVideoProduct($idVideo)
        {
            self::setDefaultDatabaseOption();
            $option = DigitalSignage4_caller::getInstance()->get_data(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT);
            foreach ($option as $productID => $videoID) {
                if ($idVideo == $videoID) {
                    try {
                        $option[$productID] = self::getLastIdVideoForProduct($productID);
                    } catch (Exception $ignore) {
                        unset($option[$productID]);
                    }
                }
            }
            DigitalSignage4_caller::getInstance()->save_data(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT, $option);
        }

        private static function setDefaultDatabaseOption()
        {
            if (!DigitalSignage4_caller::getInstance()->get_data(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT)) {
                DigitalSignage4_caller::getInstance()->save_data(DigitalSignage4_caller::DISPLAYED_VIDEO_PODUCT, array());
            }
        }

        private static function getLastIdVideoForProduct($idProduct)
        {
            $demandeManager = new DigitalSignage4_DemandeManager(DigitalSignage4_caller::getInstance());
			$sql="SELECT `id_demande` FROM ".DigitalSignage4_caller::get_video_table_name()." WHERE `flag` = 'completed' AND  `product_id` =%d ORDER BY `id_demande` DESC  LIMIT 1 ";
			global $wpdb;
            $sql=$wpdb->prepare($sql,$idProduct);
			
			$videosDatabase = $demandeManager->getLocalDemandes($sql);
            if (isset($videosDatabase[0]) && $videosDatabase[0] instanceof DigitalSignage4_DemandeEntity) {
                return $videosDatabase[0]->getIdDemande();
            }
            throw new Exception("Not found");
        }
    }
