<?php

/**
 * Copyright (c) 2013, Kairat Bakytow
 * All rights reserved.

 * ATTENTION: This commercial software is intended for use with Oxwall Free Community Software http://www.oxwall.org/
 * and is licensed under Oxwall Store Commercial License.
 * Full text of this license can be found at http://www.oxwall.org/store/oscl
 */

OW::getRouter()->addRoute( new OW_Route('smileys.admin', 'smileys/admin', 'SMILEYS_CTRL_Admin', 'index') );
OW::getRouter()->addRoute( new OW_Route('smileys.admin-rsp', 'smileys/admin-rsp', 'SMILEYS_CTRL_Admin', 'smileysRsp') );
OW::getRouter()->addRoute( new OW_Route('smileys.smileLoader', 'smileys/loader', 'SMILEYS_CTRL_Smileys', 'getSmileysByCategory') );

$eventManager = OW::getEventManager();

function smileys_after_master_page_render( OW_Event $event )
{
    SMILEYS_CLASS_HtmlDocument::getInstance()->replaceBaseWysisyg();
    SMILEYS_CLASS_HtmlDocument::getInstance()->replaceBaseComment();
    
    $cmp = new SMILEYS_CMP_Panel();
    OW::getDocument()->appendBody($cmp->render());
}
$eventManager->bind( OW_EventManager::ON_BEFORE_DOCUMENT_RENDER, 'smileys_after_master_page_render', 99 );

function smileys_comments_handler( OW_Event $event )
{
    if ( !empty($_GET['cmpClass']) )
    {
        switch ( $_GET['cmpClass'] )
        {
            case 'BASE_CMP_CommentsForm':
                SMILEYS_CLASS_HtmlDocument::getInstance()->addSmileysToComment();
                break;
            case 'QUESTIONS_CMP_Question':
            case 'EQUESTIONS_CMP_Question':
                OW::getDocument()->addOnloadScript( 'var smileysContent=$(".q-text:first");smileysContent.html(smileysContent.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));' );
                break;
        }
    }
    
    OW::getEventManager()->bind( 'feed.on_entity_add', 'smileys_entity_add' );
    OW::getEventManager()->bind( 'feed.on_entity_update', 'smileys_entity_update' );
    OW::getEventManager()->bind( 'feed.on_item_render', 'smileys_feed_on_item_render');
    
    if ( OW::getPluginManager()->isPluginActive('questions') || OW::getPluginManager()->isPluginActive('equestions') )
    {
        return;
    }
    
    OW::getEventManager()->bind( 'feed.get_status_update_cmp', 'smileys_feed_get_status_update_cmp' );
}
$eventManager->bind( OW_EventManager::ON_AFTER_ROUTE, 'smileys_comments_handler' );

function smileys_entity_add( OW_Event $event )
{
    $params = $event->getParams();
    $data = $event->getData();

    switch ( $params['entityType'] )
    {
        case 'blog-post':
            $post = PostService::getInstance()->findById( $params['entityId'] );
            $url = OW::getRouter()->urlForRoute( 'post', array('id' => $post->id) );
                    
            $post->post = preg_replace( SMILEYS_CLASS_HtmlDocument::PATTERN, '', strip_tags(UTIL_String::truncate($post->post, 1000, '...'), '<img>') );
            $content = nl2br( $post->post );
            $title = UTIL_String::truncate( strip_tags($post->title), 100, '...' );  
            
            $data = array(
                'time' => $post->timestamp,
                'ownerId' => $post->authorId,
                'content' => '<a href="' . $url . '">' . $title . '</a><div class="ow_remark" style="paddig-top: 4px">' . $content . '</div>',
                'view' => array('iconClass' => 'ow_ic_write')
            );
            break;
        case 'forum-topic':
            $topicId = (int)$params['entityId'];
            $service = FORUM_BOL_ForumService::getInstance();
            $topicDto = $service->findTopicById( $topicId );
            $postDto = $service->findTopicFirstPost( $topicId );
            $groupDto = $service->findGroupById( $topicDto->groupId );
            $sectionDto = $service->findSectionById( $groupDto->sectionId );
            $isHidden = (bool)$sectionDto->isHidden;

            if ( $postDto === null )
            {
                return;
            }

            if ( $groupDto->isPrivate )
            {
                return;
            }

            $topicUrl = OW::getRouter()->urlForRoute( 'topic-default', array('topicId' => $topicDto->id) );
            $content = preg_replace( SMILEYS_CLASS_HtmlDocument::PATTERN, '', strip_tags(UTIL_String::truncate($postDto->text, 1000, '...'), '<img>') );
            $title = UTIL_String::truncate( strip_tags($topicDto->title), 100, '...' );

            $data = array(
                'features' => array( 'likes' ),
                'ownerId' => $topicDto->userId,
                'time' => (int) $postDto->createStamp,
                'content' => '<div class="ow_newsfeed_item_content" style="float: none">
                        <a class="ow_newsfeed_item_title" href="' . $topicUrl . '">' . $title . '</a>
                        <div class="ow_remark ow_smallmargin">' . $content . '</div>
                        <div class="ow_newsfeed_action_activity forum_newsfeed_activity">[ph:activity]</div>
                    </div>',
                'view' => array(
                    'iconClass' => 'ow_ic_forum'
                ),
                'string' => OW::getLanguage()->text( 'forum', 'feed_activity_topic_string' ),
                'toolbar' => array(array(
                        'href' => $topicUrl,
                        'label' => OW::getLanguage()->text( 'forum', 'feed_toolbar_discuss' )
                ))
            );

            if ( $isHidden )
            {
                $data['params']['feedType'] = $sectionDto->entity;
                $data['params']['feedId'] = $groupDto->entityId;
                $data['params']['visibility'] = 2 + 4 + 8;
                $data['params']['postOnUserFeed'] = false;
                $data['contextFeedType'] = $data['params']['feedType'];
                $data['contextFeedId'] = $data['params']['feedId'];
            }
            break;
    }

    $event->setData( $data );
}

function smileys_entity_update( OW_Event $event )
{
    $params = $event->getParams();
    $data = $event->getData();

    switch ( $params['entityType'] )
    {
        case 'blog-post':
            $service = PostService::getInstance();
            $post = $service->findById($params['entityId']);

            $url = OW::getRouter()->urlForRoute('post', array('id' => $post->id));

            $content = nl2br(preg_replace(SMILEYS_CLASS_HtmlDocument::PATTERN, '', strip_tags(UTIL_String::truncate($post->post, 1000, '...'), '<img>')) );
            $title = UTIL_String::truncate(strip_tags($post->title), 100, '...');

            $data = array(
                'time' => (int) $post->timestamp,
                'ownerId' => $post->authorId,
                'content' => '<a href="' . $url . '">' . $title . '</a>
                    <div class="ow_remark" style="paddig-top: 4px">' . $content . '</div>',
                'view' => array(
                    'iconClass' => 'ow_ic_write'
                ),
                'actionDto' => $data['actionDto']
            );
            break;
    }

    $event->setData($data);
}

function smileys_feed_on_item_render( OW_Event $event )
{
    $params = $event->getParams();
    $entityTypes = array('forum-topic', 'user-comment', 'question');
    
    if ( OW::getPluginManager()->isPluginActive('commenteditor') )
    {
        $entityTypes[] = 'user-status';
    }
    
    if ( !in_array($params['action']['entityType'], $entityTypes) )
    {
        return;
    }
    
    $data = $event->getData();
    $language = OW::getLanguage();

    switch ( $params['action']['entityType'] )
    {
        case 'forum-topic':
            $service = FORUM_BOL_ForumService::getInstance();
            $postCount = $service->findTopicPostCount( $params['action']['entityId'] ) - 1;

            if ( !$postCount )
            {
                return;
            }

            $event->setData($data);

            $postIds = array();
            foreach ( $params['activity'] as $activity )
            {
                if ( $activity['activityType'] == 'forum-post' )
                {
                    $postIds[] = $activity['data']['postId'];
                }
            }

            if ( empty($postIds) )
            {
                return;
            }

            $postDto = null;
            foreach ( $postIds as $pid )
            {
                $postDto = $service->findPostById( $pid );
                if ( $postDto !== null )
                {
                    break;
                }
            }

            if ( $postDto === null )
            {
                return;
            }

            $postUrl = $service->getPostUrl( $postDto->topicId, $postDto->id );
            
            $content = preg_replace( SMILEYS_CLASS_HtmlDocument::PATTERN, '', strip_tags(UTIL_String::truncate(str_replace("&nbsp;", '', $postDto->text), 1000, '...'), '<img>') );
            $usersData = BOL_AvatarService::getInstance()->getDataForUserAvatars( array($postDto->userId), true, true, true, false );

            $avatarData = $usersData[$postDto->userId];
            $postUrl = $service->getPostUrl( $postDto->topicId, $postDto->id );

            $ipcContent = OW::getThemeManager()->processDecorator( 'mini_ipc', array(
                    'avatar' => $avatarData, 'profileUrl' => $avatarData['url'], 'displayName' => $avatarData['title'], 'content' => $content) );

            $data['assign']['activity'] = array('template' => 'activity', 'vars' => array(
                    'title' => $language->text('forum', 'feed_activity_last_reply', array('postUrl' => $postUrl)),
                    'content' => $ipcContent
                ));
            break;
        case 'user-comment':
        case 'question':
            if ( isset($data['string']['vars']['comment']) )
            {
                $data['string']['vars']['comment'] = preg_replace( '/\[([^\/]+\/[^\/]+)\]/', '<img src="' . OW::getPluginManager()->getPlugin('smileys')->getUserFilesUrl() . 'images/' . '${1}.gif" />', $data['string']['vars']['comment'] );
            }
            else
            {
                $data['string'] = preg_replace( '/\[([^\/]+\/[^\/]+)\]/', '<img src="' . OW::getPluginManager()->getPlugin('smileys')->getUserFilesUrl() . 'images/' . '${1}.gif" />', $data['string'] );
            }
            break;
        case 'user-status':
            OW::getDocument()->addScriptDeclarationBeforeIncludes(
                UTIL_JsGenerator::composeJsString('
                    ;window["commentedotir-user-status" + {$actionId}] = {$status}
                    ',
                    array(
                        'actionId' => $params['action']['id'],
                        'status' => UTIL_HtmlTag::autoLink($data['data']['status'])
                    )
                )
            );
            
            if ( isset($data['string']['vars']['comment']) )
            {
                $data['string']['vars']['comment'] = preg_replace( '/\[([^\/]+\/[^\/]+)\]/', '<img src="' . OW::getPluginManager()->getPlugin('smileys')->getUserFilesUrl() . 'images/' . '${1}.gif" />', $data['string']['vars']['comment'] );
            }
            elseif ( isset($data['data']['status']) )
            {
                $data['data']['status'] = preg_replace( '/\[([^\/]+\/[^\/]+)\]/', '<img src="' . OW::getPluginManager()->getPlugin('smileys')->getUserFilesUrl() . 'images/' . '${1}.gif" />', $data['data']['status'] );
            }
            else
            {
                $data['string'] = preg_replace( '/\[([^\/]+\/[^\/]+)\]/', '<img src="' . OW::getPluginManager()->getPlugin('smileys')->getUserFilesUrl() . 'images/' . '${1}.gif" />', $data['string'] );
            }
            break;
    }

    $event->setData($data);
}

function smileys_feed_get_status_update_cmp( OW_Event $event )
{
    SMILEYS_CLASS_HtmlDocument::getInstance()->addSmileToNewsfeedUpdateStatus( $event );
}

function smileys_mailbox_message_render( OW_Event $event )
{
    $data = $event->getData();
    $data['short'] = nl2br(preg_replace(SMILEYS_CLASS_HtmlDocument::PATTERN, '', strip_tags(UTIL_String::truncate($data['full'], 1000, '...'), '<img>')) );
    $event->setData( $data );
}
$eventManager->bind( 'mailbox.message_render', 'smileys_mailbox_message_render' );

function smileys_base_ping_consoleUpdate( OW_Event $event )
{
    if ( OW::getRequest()->isAjax() )
    {
        return;
    }
    
    if ( OW::getPluginManager()->isPluginActive('questions') || OW::getPluginManager('equestions') )
    {
        $javaScripts = OW::getDocument()->getJavaScripts();

        foreach ( $javaScripts['items'][1000]['text/javascript'] as &$script )
        {
            if ( strpos($script, 'ow_static/plugins/base/js/console.js') !== false )
            {
                $script = OW::getPluginManager()->getPlugin( 'smileys' )->getStaticJsUrl() . 'console.js';

                OW::getDocument()->setJavaScripts( $javaScripts );

                break;
            }
        }
    }
}
$eventManager->bind( 'base.ping.consoleUpdate', 'smileys_base_ping_consoleUpdate' );

function smileys_questions_on_question_render( OW_Event $event )
{
    $data = $event->getData();
    $data['text'] = preg_replace( '/\[([^\/]+\/[^\/]+)\]/', '<img src="' . OW::getPluginManager()->getPlugin('smileys')->getUserFilesUrl() . 'images/' . '${1}.gif" />', $data['text'] );
    $event->setData( $data );
}
$eventManager->bind( 'questions.on_question_render', 'smileys_questions_on_question_render' );

function smileys_questions_on_list_item_render( OW_Event $event )
{
    $data = $event->getData();
    $data['text'] = preg_replace( '/\[([^\/]+\/[^\/]+)\]/', '<img src="' . OW::getPluginManager()->getPlugin('smileys')->getUserFilesUrl() . 'images/' . '${1}.gif" />', $data['text'] );
    $event->setData( $data );
}
$eventManager->bind( 'questions.on_list_item_render', 'smileys_questions_on_list_item_render' );

function smileys_base_splash_screen_exceptions( BASE_CLASS_EventCollector $event )
{
    $event->add( array(OW_RequestHandler::ATTRS_KEY_CTRL => 'BASE_CTRL_AjaxLoader', OW_RequestHandler::ATTRS_KEY_ACTION => 'component') );
}
$eventManager->bind( 'base.splash_screen_exceptions', 'smileys_base_splash_screen_exceptions' );

function smileys_console_collect_items(OW_Event $event )
{
    $javaScripts = OW::getDocument()->getJavaScripts();
    
    if ( !empty($javaScripts['items'][3001]) )
    {
        foreach ( $javaScripts['items'][3001]['text/javascript'] as $key => $script )
        {
            if ( strpos($script, 'ow_static/plugins/mailbox/js/contactmanager.js') !== false )
            {
                $javaScripts['items'][3001]['text/javascript'][$key] = OW::getPluginManager()->getPlugin('smileys')->getStaticJsUrl() . 'contactmanager.js';

                break;
            }
        }
    }
    
    if ( !empty($javaScripts['items'][3008]) )
    {
        foreach ( $javaScripts['items'][3008]['text/javascript'] as $key => $script )
        {
            if ( strpos($script, 'ow_static/plugins/mailbox/js/conversation_list.js') !== false )
            {
                $javaScripts['items'][3008]['text/javascript'][$key] = OW::getPluginManager()->getPlugin('smileys')->getStaticJsUrl() . 'conversation_list.js';

                break;
            }
        }
    }
    
    OW::getDocument()->setJavaScripts($javaScripts);
}
//OW::getEventManager()->bind('console.collect_items', 'smileys_console_collect_items', 3003);
