<?php

/**
 * TbGridView class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package bootstrap.widgets
 */
Yii::import('bootstrap.widgets.TbGridView');

/**
 * Bootstrap Zii grid view.
 */
class PlGridView extends TbGridView
{
    /*
      Set custom keys for lokalisation
     */

    public $summaryText = '{start}-{end}/{count}';
    public $brandUrl = '#';
    public $enableAddButton = true;
    public $enableSearchButton = true;
    public $enableHeaderTranslation = true;
    public $navBarHtmlOptions;
    public $showAlertBlock = false;
    public $alertOptions;
    public $alertAutoHide = true;
    public $headerAttribute = null;
    public $customButtons = array();
    public $headerTitle;
    public $addButtonTitle;
    public $searchButtonTitle;
    public $modalCreateHeader;
    public $modalUpdateHeader;
    public $headerCreateUrl;
    public $createInModal = true;
    public $hideHeaderButtons = false;
    public $modalId;
    public $searchBtnId;
    public $createBtnId;
    public $type = 'striped bordered condensed';
    public $itemsCssClass = 'plTable';
    public $modalSize = null; // null, 'large', 'small', 'huge'
    public $modalHeight = null; // null, 'full'
    public $hideDeleteButton = true;
    public $modalHelpKey = null;
    public $autoRefreshTimer = 0;
    //public $ajaxUpdate = false;
    // Disable header history e.g using multiple grids on same page
    public $enableHistory = false;
    public $afterAjaxUpdate = "function(id,data){        $('#'+id+'-summary div').text($(data).find('#'+id+' .summary').text());}";
    public $navBarTitleAppend = '';
    public $showNavbar = true;
    public $useCustomTitle = false;
    public $showHelpBtn = true;
    public $helpBtnUrl = null;

    public function init()
    {
        parent::init();

        if (!$this->headerCreateUrl) {
            $this->headerCreateUrl = Yii::app()->controller->createUrl("create");
        }

        if (!isset($this->modalCreateHeader)) {
            $this->modalCreateHeader = "GENERAL_MODAL_CREATE_HEADER";
        }

        if (!isset($this->modalUpdateHeader)) {
            $this->modalUpdateHeader = "GENERAL_MODAL_UPDATE_HEADER";
        }

        $this->modalId = $this->id . '_Modal';
        $this->searchBtnId = $this->id . 'SearchBtn';
        $this->createBtnId = $this->id . 'CreateBtn';
    }

    /**
     * Creates column objects and initializes them.
     */
    protected function initColumns()
    {
        foreach ($this->columns as $i => $column) {
            if (is_array($column) && !isset($column['class'])) {
                $this->columns[$i]['class'] = 'ext.PlGrid.PlDataColumn';
            }
        }
        parent::initColumns();
    }

    public function run()
    {
        echo '<div class="activeGrid">';
        if ($this->showNavbar) {
            $this->renderNavBar();
        }
        $this->renderAlertBlock();
        parent::run();
        $this->renderModalWindow();
        echo '</div>';

        if ($this->autoRefreshTimer != 0) {
            $this->setupAutoRefresh();
        }
    }

    private function generateTranslationId($suffix = '')
    {
        $result  = $suffix;
        if (!$this->useCustomTitle){
            $result = strtoupper(Yii::app()->controller->module->id . '_' . $suffix);
        }
        return $result;
    }

    /**
     * Render grid header with create and search button
     */
    private function renderNavBar()
    {
        $this->renderSummary();

        $addBtnScript = '';
        
        if ($this->createInModal) {
            $addBtnScript = "$('#" . $this->createBtnId . "').click(function(){
                $('#" . $this->modalId . " .modal-header h4').html(\"" . __($this->modalCreateHeader) . "\");
                $('#" . $this->modalId . " .modal-header h4').attr('data-translation-target','MODAL_HEADER_TITLES');
                $('#" . $this->modalId . "_deleteBtn').hide();
                $.ajax({
                    url: '" . $this->headerCreateUrl . "',
                })
                .success(function(data) {
                    $('#" . $this->modalId . " .modal-body').html(data);
                    $('#" . $this->modalId . "').modal('show');
                 });
              });";
        }


        Yii::app()->clientScript->registerScript('search', "
            $('#" . $this->searchBtnId . "').click(function(){
                $(this).parent().toggleClass('active');
                $(this).closest('.activeGrid').toggleClass('search');
                return false;
            });


          " . $addBtnScript . "

          $('#" . $this->modalId . "').on('shown', function () {


              $('#" . $this->modalId . "').find('input[type=text],input[type=password],input[type=file],textarea,select').filter(':visible:first').focus();
              $('.modal-backdrop').unbind('click');

              $('#" . $this->modalId . "').on('keyup', this, function(e){
                if(e.keyCode == 13 && $(this).is(':visible')){
                    if ($('*:focus').prop('localName') !== 'textarea') {
                        $('#" . $this->modalId  . "_saveBtn').click();
                    }
                }
              });
          });


          $('#" . $this->modalId . "').on('hide', function () {
              $('#" . $this->modalId . "').unbind('keyup');
          });

        function stopKeyPress() {
            var evt = (event) ? event : null;
            if ((evt.keyCode === 13)) {
                return false;
            }
        }
        document.onkeypress = stopKeyPress;

        ", null);

        if ($this->filter) {
            $this->activateSearchFieldAfterPageReload();
            //TEST
            Yii::app()->clientScript->registerScript('updateModalHeaders', "
          $('#" . $this->modalId . "').on('show', function () {
            var headerAttribute = '" . $this->headerAttribute . "';
            if (headerAttribute) {

                var modelName = '" . $this->filter->modelName . "';
                var headerAttributeValue = $('#" . $this->modalId . "').find('#'+modelName+'_'+headerAttribute).val();
                if (headerAttributeValue) {
                    $('h4').text(\"" . __($this->modalUpdateHeader) . ": \"+headerAttributeValue);
                }
            }
          });
        ", null);
        }

        $cssClass = 'pull-right';
        $helpBtn = '';
        if ($this->showHelpBtn) {
            $helpBtn = '<div class="' . $cssClass . '" id="' . $this->id . '-summary" title="' . __('GLOBAL_HELP_BTN') . '" data-translation-id="GLOBAL_HELP_BTN">' . $this->getSummary() . Yii::app()->controller->getHelpLink($this->helpBtnUrl) . '</div>';
        }
        $this->widget('bootstrap.widgets.TbNavbar', array(
            'collapse' => true,
            'fixed' => false,
            'brandUrl' => $this->brandUrl,
            'brand' => $this->getNavBarHeaderTitle(),
            'htmlOptions' => $this->getNavBarHtmlOptions(),
            'items' => $this->getNavBarItems(),
            'items' => array(
                array(
                    'class' => 'bootstrap.widgets.TbMenu',
                    'items' => $this->getNavBarItems()
                ),
                $helpBtn,
                $this->renderCustomButton($cssClass),
            )
                )
        );
    }

    protected function getNavBarHeaderTitle()
    {
        $headerTitle = $this->headerTitle . $this->navBarTitleAppend;
        if ($this->enableHeaderTranslation) {
            $headerTitle = __($this->generateTranslationId($this->headerTitle)) . $this->navBarTitleAppend;
        }
        return $headerTitle;
    }

    protected function activateSearchFieldAfterPageReload()
    {
        $dataProvider = new CPhonalisaDataProvider(get_class($this->filter));
        if (isset($_GET[get_class($dataProvider->model)])) {
            Yii::app()->clientScript->registerScript('activateSearchFieldIfNeeded', "
                    $('.activeGrid').addClass('search');
                    $('.activeGrid .nav-collapse .icon-search').parent().parent().addClass('active');", null
            );
        }
    }

    protected function renderCustomButton($cssClass)
    {
        $items = '';
        foreach ($this->customButtons as $key => $value) {
            $button = $this->getCustomButton($key);
            $items = $this->getCustomButtonItems($button, $cssClass, $items);
            if (!is_int($key)) {
                break;
            }
        }
        return $items;
    }

    protected function getCustomButton($key)
    {
        $button = @$this->customButtons;
        if (is_int($key)) {
            $button = @$this->customButtons[$key];
        }
        return $button;
    }

    protected function getCustomButtonItems($button, $cssClass, $items)
    {
        if (isset($button['position']) && $button['position'] === 'right') {
            $items = array(
                'class' => 'bootstrap.widgets.TbMenu',
                'htmlOptions' => array('class' => $cssClass),
                'items' => $this->getCustomButtons('', $button),
            );
        }
        return $items;
    }

    /**
     *  documentation : http://www.cniska.net/yii-bootstrap/#tbAlert
     * */
    public function renderAlertBlock()
    {

        if ($this->showAlertBlock) {
            $this->widget('bootstrap.widgets.TbAlert', $this->getAlertOptions());

            if ($this->alertAutoHide) {
                Yii::app()->clientScript->registerScript(
                        'autoHideAlert', 'setTimeout(function(){$(".alert").alert("close")}, 5000);', CClientScript::POS_READY
                );
            }
        }
    }

    public function getAlertOptions()
    {
        $alertOptions = array();
        if (!isset($this->alertOptions) || !empty($this->alertOptions)) {
            $alertOptions = array(
                'block' => true, // display a larger alert block?
                'fade' => true, // use transitions?
                'closeText' => '&times;', // close link text - if set to false, no close link is displayed
                    //'alerts'=>array(   // configurations per alert type
                    //    'error'=>array('block'=>true, 'fade'=>true, 'closeText'=>'&times;'),
                    //    'success'=>array('block'=>true, 'fade'=>true, 'closeText'=>'&times;'), // success, info, warning, error or danger
                    //),
            );
        } else {
            $alertOptions = $this->alertOptions;
        }
        return $alertOptions;
    }

    /**
     * Return the summary text.
     */
    public function getSummary()
    {
        ob_start();
        parent::renderSummary();
        $result = ob_get_contents();
        ob_end_clean();

        if ($result == '') {
            $result = '<div class="summary">&nbsp;</div>';
        }
        return $result;
    }

    /**
     * Render hidden the summary text.
     */
    public function renderSummary()
    {
        ob_start();
        parent::renderSummary();
        $result = ob_get_contents();
        $result = str_replace('<div', '<div style="display:none"', $result);
        ob_end_clean();
        echo $result;
    }

    public function renderModalWindow()
    {
        $this->beginWidget('bootstrap.widgets.TbModal', array(
            'id' => $this->modalId,
            'htmlOptions' => array(
                'class' => $this->getModalSizeCssClass(),
            ),
            'options' => array(
            //'backdrop'=>false,
            //'keyboard'=>true
            ),
        ));

        echo '
            <div class="modal-header">
                <a class="close" data-dismiss="modal">&times;</a>';
        echo '<h4 data-translation-target="MODAL_HEADER_TITLES" >Modal header</h4>';
        if (Yii::app()->user->translateMode) {
            echo '<i data-translation-id="' . $this->modalCreateHeader . '" data-translation-target="MODAL_HEADER_TITLES"></i>';
            echo '<i data-translation-id="' . $this->modalUpdateHeader . '" data-translation-target="MODAL_HEADER_TITLES"></i>';
        }

        echo '
            </div>
            <div class="modal-body">
                <p>One fine body...</p>
            </div>
            <div class="modal-footer">';


        $saveBtnId = $this->modalId . '_saveBtn';
        $deleteBtnId = $this->modalId . '_deleteBtn';

        if (!$this->hideDeleteButton) {

            $this->widget('bootstrap.widgets.TbButton', array(
                'buttonType' => 'button',
                'type' => 'danger',
                'icon' => 'trash',
                //'label'=>__('GLOBAL_DELETE_BUTTON'),
                'url' => '#',
                'loadingText' => __('GLOBAL_LOADING_TEXT'),
                'htmlOptions' => array('id' => $deleteBtnId, 'class' => 'modalDeleteBtn pull-left'),
            ));
        }

        $this->widget('bootstrap.widgets.TbButton', array(
            'buttonType' => 'link',
            //'type'=>'danger',
            'icon' => 'icon-question',
            'url' => Yii::app()->controller->getHelpUrl($this->modalHelpKey, true),
            'encodeLabel' => false,
            'htmlOptions' => array(
                //'id'=>$deleteBtnId,
                'target' => "_blank",
                'class' => 'pull-left',
                'data-translation-id' => 'GLOBAL_HELP_BTN',
                'title' => __('GLOBAL_HELP_BTN')
            ),
        ));


        $this->widget('bootstrap.widgets.TbButton', array(
            'buttonType' => 'button',
            'type' => 'primary',
            'label' => __('GLOBAL_SAVE_BUTTON'),
            'loadingText' => __('GLOBAL_LOADING_TEXT'),
            'htmlOptions' => array('id' => $saveBtnId, 'class' => 'modalSaveBtn'),
        ));

        if($this->modalHeight  !== null) {
            Yii::app()->clientScript->registerScript("windowResize", "

                function resizeModal() {
                    if  ( $(window).height() <= 800 ) {
                        $('.modal-body').closest('.modal').removeClass('modal_height-full');
                    } else {
                        $('.modal-body').closest('.modal').addClass('modal_height-full');
                    }
                }

                $('#".$this->modalId."').on('show', function() {
                    resizeModal()
                });

                window.addEventListener('resize', function() {
                    resizeModal()
                }, true);
            ");
        }

        Yii::app()->clientScript->registerScript('modalSaveBtn', "$('#" . $saveBtnId . "').click(function() {
            $('#" . $this->id . "_hiddenSaveBtn').click();
        });");

        Yii::app()->clientScript->registerScript('editOnDoubleClick', "$('#content').on('dblclick','#" . $this->id . " tbody tr', function(e) {
            $(this).find('a.update').click();     
        });");

        Yii::app()->clientScript->registerScript('modalDeleteBtn', "$('#" . $deleteBtnId . "').click(function() {
            if(confirm('" . __('GLOBAL_DELETE_CONFIRM') . "')){
                var btn = $(this);
                var hiddenBtn = $('#" . $this->id . "_hiddenSaveBtn');
                btn.button('loading');
                $('<input>').attr({name: 'deleteRequest', value:'true'}).insertAfter(hiddenBtn);
                hiddenBtn.click();
            }

        });");

        $this->widget('bootstrap.widgets.TbButton', array(
            'label' => __('GLOBAL_CANCEL_BUTTON'),
            'url' => '#',
            'htmlOptions' => array('data-dismiss' => 'modal'),
        ));

        echo '</div>';

        $this->endWidget();
    }

    protected function getModalSizeCssClass()
    {
        $class = "";
        if ($this->modalSize) {
            $class.= "modal-" . $this->modalSize;
        }
        if ($this->modalHeight) {
            $class.= " modal_height-" . $this->modalHeight;
        }
        return $class;
    }

    public function getNavBarHtmlOptions()
    {

        if ($this->navBarHtmlOptions) {
            if ($this->enableHeaderTranslation == true) {
                $this->navBarHtmlOptions['data-translation-id'] = $this->generateTranslationId($this->headerTitle);
            }
            return $this->navBarHtmlOptions;
        } else {
            return array(
                'data-translation-id' => $this->generateTranslationId($this->headerTitle),
            );
        }
    }

    private function getCustomButtons($items = '', $customButton = '')
    {
        if (!$customButton) {
            $customButton = $this->customButtons;
        }

        foreach ($customButton as $button) {
            if (!is_array($button)) {
                $items[] = $customButton;
                break;
            }
            $items[] = $button;
        }
        return $items;
    }

    private function getNavBarItems()
    {
        if ($this->hideHeaderButtons) {
            return array();
        }

        $items = array();
        $items[] = '---';

        foreach ($this->customButtons as $key => $value) {
            $button = $this->getCustomButton($key);
            if (!isset($button['position']) || $button['position'] !== 'right') {
                $items = $this->getCustomButtons($items, $button);
            }
            if (!is_int($key)) {
                break;
            }
        }

        if ($this->enableAddButton) {
            $items[] = array(
                'label' => __($this->addButtonTitle ? $this->generateTranslationId($this->addButtonTitle) : 'GENERAL_ADD'),
                'url' => $this->createInModal ? '#' : $this->headerCreateUrl,
                'icon' => 'plus',
                'linkOptions' => array(
                    'id' => $this->createBtnId,
                    'data-target' => '#' . $this->modalId,
                    'data-translation-id' => $this->addButtonTitle ? $this->generateTranslationId($this->addButtonTitle) : 'GENERAL_ADD',
                )
            );
        }

        if ($this->enableSearchButton) {
            $items[] = array(
                'label' => __($this->searchButtonTitle ? $this->generateTranslationId($this->searchButtonTitle) : 'GENERAL_SEARCH'),
                'url' => '#',
                'icon' => 'search',
                'linkOptions' => array(
                    'id' => $this->searchBtnId,
                    'data-translation-id' => $this->searchButtonTitle ? $this->generateTranslationId($this->searchButtonTitle) : 'GENERAL_SEARCH'
                ),
            );
        }

        return $items;
    }

    private function setupAutoRefresh()
    {
        Yii::app()->clientScript->registerScript('gridAutoRefresh', "setInterval(function(){
            if(document.activeElement.type != 'text' && document.activeElement.name != 'pageSize' && document.activeElement.className != 'dropdownSearchField'){
                $.fn.yiiGridView.update('" . $this->id . "');
            }            
        }," . $this->autoRefreshTimer . ");");
    }
}
