<?php

require_once MAX_PATH . '/lib/OA.php';
require_once MAX_PATH . '/lib/max/Plugin/Common.php';
require_once LIB_PATH . '/Extension/bannerTypeHtml/bannerTypeHtml.php';
require_once MAX_PATH . '/lib/max/Plugin/Translation.php';

class Plugins_BannerTypeHTML_revealads_revealadsComponent extends Plugins_BannerTypeHTML
{
    /**
     * Return type of plugin
     *
     * @return string A string describing the type of plugin.
     */
	 
    function getStorageType()
    {
        return 'html';
    }

    /**
     * Return the media (content) type
     *
     */
    function getContentType()
    {
        return 'html';
    }
	 
    function getOptionDescription()
    {
        return $this->translate("Reveal Ads");
    }

    function validateForm(&$form)
    {
        return true;
    }


    function processForm($insert, $bannerid, $aFields,$aVariables)
    {
		$aFields['type'] = 'web';

		$aBanner['storagetype'] = 'web'	;
		
		if (!empty($_FILES['upload']) && $_FILES['upload']['size'] > 0) { //TODO refactor upload to be a valid quickform elem
			$oFile = OA_Creative_File::factoryUploadedFile('upload');
			checkForErrorFileUploaded($oFile);
			$oFile->store($aFields['type']);
			$aFile = $oFile->getFileDetails();

			if (!empty($aFile)) {
				
				$aVariables['filename']      = $aFile['filename'];
				$aVariables['contenttype']   = 'png';
			}

			$aVariables['pluginversion'] = $aFile['pluginversion'];
			$editSwf                     = $aFile['editswf'];
				
			// Delete old file for this banner
			if (!empty($aBanner['filename']) && ($aBanner['filename'] != $aFile['filename'])) {
				DataObjects_Banners::deleteBannerFile($aBanner['storagetype'], $aBanner['filename']);
			}
		}
		
		if (!empty($_FILES['uploadalt']) && $_FILES['uploadalt']['size'] > 0) {

			//TODO: Check image only.
			$oFile = OA_Creative_File::factoryUploadedFile('uploadalt');
			checkForErrorFileUploaded($oFile);
			$oFile->store($aFields['type']);
			$aFile = $oFile->getFileDetails();

			if (!empty($aFile)) {
				$aVariables['alt_filename']    = $aFile['filename'];
				$aVariables['alt_contenttype'] = $aFile['contenttype'];
			}
		}

		$doBanners = OA_Dal::factoryDO('banners');
		
		// Get existing banner details
		if (!empty($bannerid)) {
			if ($doBanners->get($bannerid)) {
				$aBanner = $doBanners->toArray();
			}
		}
	
		$doBanners->setFrom($aVariables);			
		$doBanners->update();
								
		return true;
    }
	
    function preprocessForm($insert, $bannerid, &$aFields, &$aVariables)
    {
		return true;		
    }
	
    function buildForm(&$form, &$row)
    {
		$type = 'web';

        $imageName = _getContentTypeIconImageName($row['contenttype']);
        $size = _getBannerSizeText($type, $row['filename']);

        addUploadGroup($form, $aBanner,
            array(
                'uploadName' => 'upload',
                'radioName' => 'replaceimage',
                'imageName'  => $imageName,
                'fileName'  => $row['filename'],
                'fileSize'  => $size,
                'newLabel'  => "Select the Reveal image you want to use for this banner",
                'updateLabel'  => "Do you wish to keep your existing video, or do you want to upload another? ",
                'handleSWF' => true
              )
        );

        $altImageName = _getContentTypeIconImageName($row['alt_contenttype']);
        $altSize = _getBannerSizeText($type, $row['alt_filename']);

        $aUploadParams = array(
                'uploadName' => 'uploadalt',
                'radioName' => 'replacealtimage',
                'imageName'  => $altImageName,
                'fileSize'  => $altSize,
                'fileName'  => $row['alt_filename'],
                'newLabel'  => "Select the narrow image you want to use for this banner ",
                'updateLabel'  => "Do you wish to keep your existing image, or do you want to upload another? ",
                'handleSWF' => false
              );

        addUploadGroup($form, $row, $aUploadParams);

	
        $form->addElement('header', 'header_b_links', "Banner link");
        $form->addElement('text', 'url', $GLOBALS['strURL']);		
        $targetElem = $form->createElement('text', 'target', $GLOBALS['strTarget']);
        $targetElem->setAttribute('maxlength', '16');
        $form->addElement($targetElem);
        $form->addElement('header', 'header_b_display', 'Banner display');

        $sizeG['width'] = $form->createElement('text', 'width', $GLOBALS['strWidth'].":");
        $sizeG['width']->setAttribute('onChange', 'oa_sizeChangeUpdateMessage("warning_change_banner_size");');
        $sizeG['width']->setSize(5);

        $sizeG['height'] = $form->createElement('text', 'height', $GLOBALS['strHeight'].":");
        $sizeG['height']->setAttribute('onChange', 'oa_sizeChangeUpdateMessage("warning_change_banner_size");');
        $sizeG['height']->setSize(5);
        $form->addGroup($sizeG, 'size', $GLOBALS['strSize'], "&nbsp;", false);
		
        $form->addElement('hidden', 'ext_bannertype', $this->getComponentIdentifier());
    }

    function checkForErrorFileUploaded($oFile)
    {
    	if (PEAR::isError($oFile)) {
    	die('here');

    	    phpAds_PageHeader(1);
    	    phpAds_Die($GLOBALS['strErrorOccurred'], htmlspecialchars($oFile->getMessage()). "<br>Please make sure you selected a valid file.");
    	}
    }

    	
    function _getContentTypeIconImageName($contentType)
    {
        $imageName = '';
        if (empty($contentType)) {
            return $imageName;
        }

        switch ($contentType) {
            case 'swf':
            case 'dcr':  $imageName = 'icon-filetype-swf.gif'; break;
            case 'jpeg': $imageName = 'icon-filetype-jpg.gif'; break;
            case 'gif':  $imageName = 'icon-filetype-gif.gif'; break;
            case 'png':  $imageName = 'icon-filetype-png.gif'; break;
            case 'rpm':  $imageName = 'icon-filetype-rpm.gif'; break;
            case 'mov':  $imageName = 'icon-filetype-mov.gif'; break;
            default:     $imageName = 'icon-banner-stored.gif'; break;
        }

        return $imageName;
    }


    function _getBannerSizeText($type, $filename)
    {
        $size = phpAds_ImageSize($type, $filename);
        if (round($size / 1024) == 0) {
             $size = $size." bytes";
        }
        else {
             $size = round($size / 1024)." Kb";
        }

        return $size;
    }
    	
}
