<?php
/**
 * @var $this \yii\web\View
 */

$this->registerJsFile('/js/zuck/dist/zuck.min.js',["position"=>$this::POS_HEAD]);
$this->registerCssFile("/js/zuck/dist/zuck.min.css");
$this->registerCssFile("/js/zuck/dist/skins/snapgram.min.css");
?>
<div class="stories_cont">
    <div id="stories"></div>
</div>
<?php use app\models\News;
$stories =  Yii::$app->cache->getOrSet("site-stories",function (){
    $data = [];
    $news = \app\models\front\News::find()->alias('news')
        ->joinWith('topics t')
        ->groupBy('news.id')
        ->andWhere(['t.id'=>157])->limit(10);
	$index = 0;
    foreach ($news->all() as $news_item)
    {
        /**
         * @var $news_item News
         */
        $comments = [];
        foreach ($news_item->getCommentsAll()->limit(5)->all() as $comment){
            /**
             * @var $comment \app\models\base\Comments
             */
            $comments[]=[
                "message"=>$comment->message,
                "published_at"=>$comment->publishedAt
            ];
        }
        $data[]=[
            "id"=>$news_item->uid,
			"index"=>$index,
            "photo"=>$news_item->preview->getUrl(\app\models\base\Image::SIZE_680x383),
            "name"=>str_replace( '"',"&quot;",$news_item->title),
            "link"=>$news_item->url,
            "lastUpdated"=>strtotime($news_item->dt_pub),
            "seen"=>false,
            "published_at"=>$news_item->publishedAt,
            "items"=>[
                [
                    "id"=>$news_item->preview->getUrl(\app\models\base\Image::SIZE_680x383),
                    "type"=>"photo",
                    "length"=>100,
                    "lastUpdated"=>strtotime($news_item->dt_pub),
                    "src"=>$news_item->preview->getUrl(\app\models\base\Image::SIZE_1040x586),
                    "preview"=>$news_item->preview->getUrl(\app\models\base\Image::SIZE_320x180),
                    "link"=>$news_item->url,
                    "linkText"=>str_replace( '"',"'",$news_item->lid),
                    "seen"=> false,
                    "lid"=>str_replace( '"',"'",$news_item->lid),
                    "post_title"=>str_replace( '"',"'",$news_item->title),
                    "comments"=>base64_encode(json_encode($comments))
                ]
            ]

        ];
		$index++;
    }
    return json_encode($data);
},60*5);

?>

<script>
    const get = function (array, what) {
        if (array) {
            return array[what] || '';
        } else {
            return '';
        }
    };
    const renderComments = function (comments){
        let html = "";
        var j;
        try{
            let commentsArr = JSON.parse(atob(comments));
            if("object" === typeof commentsArr && commentsArr.length>0){
                html+='<div class="comments">';
                for(let i = 0; i < commentsArr.length; i++){
                    j = commentsArr[i];
                    html+=`<div class="comment"><div class="message">${j.message}</div><div class="published_at">${j.published_at}</div></div>`
                }
                html+='</div>';
            }
        } catch (e){

        }
        return html;

    }
    let stories = new Zuck("stories",{
        skin: 'snapgram',
        avatars: false,         // shows user photo instead of last story item preview
        list: false,           // displays a timeline instead of carousel
        openEffect: true,      // enables effect when opening story
        cubeEffect: false,     // enables the 3d cube effect when sliding story
        autoFullScreen: false, // enables fullscreen on mobile browsers
        backButton: true,      // adds a back button to close the story viewer
        backNative: false,     // uses window history to enable back button on browsers/android
        previousTap: true,     // use 1/3 of the screen to navigate to previous item when tap the story
        localStorage: true,    // set true to save "seen" position. Element must have a id to save properly.
        reactive: false,        // set true if you use frameworks like React to control the timeline (see react.sample.html)
        rtl: false,            // enable/disable RTL
        paginationArrows:false,
        "stories": <?=$stories?>,
        template: {
            viewerItemBody: function (index, currentIndex, item) {
                return `<div
                    class="item ${get(item, 'seen') === true ? 'seen' : ''} ${currentIndex === index ? 'active' : ''}"
                    data-time="${get(item, 'time')}" data-type="${get(item, 'type')}" data-index="${index}" data-item-id="${get(item, 'id')}">
                    <div class="title"><h2><a href="${item.link}">${item.post_title}</a></h2></div>
                    ${renderComments(item.comments)}
                    ${
                    get(item, 'type') === 'video'
                        ? `<video class="media" muted webkit-playsinline playsinline preload="auto" src="${get(item, 'src')}" ${get(item, 'type')}></video>
                        <b class="tip muted">${option('language', 'unmute')}</b>`
                        : `<div class="blur-bg" style="background-image: url('${get(item, 'src')}') "></div><div class="image-container" ><img loading="auto" class="media" src="${get(item, 'src')}" ${get(item, 'type')} alt=""/></div>
                    `}

                    ${
                    get(item, 'link')
                        ? `<a class="tip link" href="${get(item, 'link')}" rel="noopener" target="_blank">
                            ${!get(item, 'linkText') || get(item, 'linkText') === '' ? option('language', 'visitLink') : get(item, 'linkText')}
                          </a>`
                        : ''
                }
                  </div>`;
            },
			timelineItem: function(itemData) {
				lazy = itemData['index'] == 5?'loading="auto" ':'';
				lazy = itemData['index'] > 5?'loading="lazy" ':lazy;
				return `<div class="story ${itemData['seen'] === true ? 'seen' : ''}">
				<a class="item-link" ${
					itemData['link'] ? `href="${itemData['link'] || ''}"` : ''
				}>
				<span class="item-preview">
				<img lazy="eager" ${lazy}src="${
					 itemData['currentPreview']
				}" alt=""/>
				</span>
				<span class="info" itemProp="author" itemScope itemType="http://schema.org/Person">
				<strong class="name" itemProp="name">${itemData['name']}</strong>
				<span class="time"></span>
				</span>
				</a>
				<ul class="items"></ul>
				</div>`;
			},
            viewerItem: function (storyData, currentStoryItem) {
                var date = new Date(storyData.lastUpdated*1000);
                return `<div class="story-viewer">
                    <div class="head">
                      <div class="left">
                        <a class="back">&lsaquo;</a>

                        <span class="item-preview">
                          <img lazy="eager" class="profilePhoto" src="${get(storyData, 'photo')}" alt="${get(storyData, 'name')}" />
                        </span>

                        <div class="info">
                          <strong class="name">${get(storyData, 'name')}</strong>
                          <span class="time">${date.toLocaleDateString()}</span>
                        </div>
                      </div>

                      <div class="right">
                        <span class="time">${get(currentStoryItem, 'timeAgo')}</span>
                        <span class="loading"></span>
                        <a class="close" tabIndex="2">&times;</a>
                      </div>
                    </div>

                    <div class="slides-pointers">
                      <div class="wrap"></div>
                    </div>
                    <div class="slides-pagination">
                      <span class="previous">&lsaquo;</span>
                      <span class="next">&rsaquo;</span>
                    </div>
                  </div>`;
            },
        }
    });
    var stories_container = document.getElementById("stories");
    addEventListener('wheel', (event) => {});

    stories_container.onwheel = (e) => {
        e.preventDefault();
        stories_container.scrollLeft+=e.wheelDeltaY
        return false;
    };
</script>
