<?php

class MessageController extends AdminController
{
    public $layout = 'treeSidebar';
    public $sidebarPages = array();
    /**
     * Default action.
     * @var string
     */
    public $defaultAction = 'index';
    /**
     * Extra information about category. Could contain:
     *  * title - Display name of category, by default it is equal to category name.
     *  * description - Category description, by default empty.
     *  * languages - Languages for translation, if specified overrides $defaultLanguages value for category.
     * @var array
     */
    public $categories = array(
        'site' => array(
            'title' => 'Общие'
        ),
    );
    /**
     * Languages for translation in category if not specified other
     * @var array
     */
    // 'ru' => 'Русский',
    public $defaultLanguages = array(
        'ru' => 'Русский',
//        'uk' => 'Украинский',
        'en' => 'Английский',
    );

    /**
     * Review & edit messages in some category for specified language
     * @param string $category Message category to display
     * @param bool $new  Specify when to display only new(without translation) messages
     * @param string $language Language
     * @return void
     */
    public function actionEdit($category = null, $new = false, $language = null)
    {
        $messageSourceTable = SourceMessage::model()->tableName();
        $messageTable = Message::model()->tableName();

        if ($language === null || $category === null)
            $this->redirect(array('index'));
        $newOnly = ($new ? 'language is null' : 'language = :lang');
        $messages = Yii::app()->db
            ->createCommand("select s.id as id, s.message as message, m.language as language, m.translation as translation from $messageSourceTable as s
                        left join $messageTable as m on (s.id=m.id and m.`language` = :lang)
                        where category=:cat order by {$newOnly}")
            ->queryAll(true, array('cat' => $category, 'lang' => $language));
        if (isset($_POST['message'])) {
            foreach ($_POST['message'] as $id => $message) if (isset($message['save']) && $message['save']) {
                $model = Message::model()->findByAttributes(
                    array('id' => $id, 'language' => $language)
                );
                if ($model === null) {
                    $model = new Message();
                    $model->id = $id;
                    $model->language = $language;
                }
                $model->translation = $message['translation'];
                $model->save();
            }
            $this->refresh();
        }
        $this->render('edit', array('messages' => $messages));
    }

    /**
     * Displays stats by category
     * @return void
     */
    public function actionIndex()
    {
        $this->render('index', array('categories' => $this->loadedCategories));
    }

    public function init()
    {

        $messageSourceTable = SourceMessage::model()->tableName();
        $messageTable = Message::model()->tableName();

        $categories = Yii::app()->db
            ->createCommand("select category, count(s.id) as all_messages from $messageSourceTable as s group by category")
            ->queryAll();
        // CVarDumper::dump($categories, 10, true);

        foreach ($categories as $i => $category) {
            if (!isset($this->categories[$category['category']])) {
                $this->categories[$category['category']] = array();
            }
            if (!isset($this->categories[$category['category']]['title'])) {
                $this->categories[$category['category']]['title'] = ucfirst($category['category']);
            }
            if (!isset($this->categories[$category['category']]['description'])) {
                $this->categories[$category['category']]['description'] = '';
            }
            if (!isset($this->categories[$category['category']]['languages'])) {
                $this->categories[$category['category']]['languages'] = $this->defaultLanguages;
            }
            foreach ($this->categories[$category['category']]['languages'] as $lang => $name) {
                $categories[$i][$lang] = Yii::app()->db
                    ->createCommand("select count(m.id) from $messageSourceTable as s left join $messageTable as m on s.id=m.id where category='{$category['category']}' and m.`language` = '$lang'")
                    ->queryScalar();
            }
        }
        $this->loadedCategories = $categories;

        $this->sidebarPages = array();

        foreach ($categories as $category)
            if ($category['category'] != 'galleryManager.main') {
                $cat = array();
                $items = array();
                foreach ($this->categories[$category['category']]['languages'] as $lang => $name) {
                    $items[$name . ' (' . $category[$lang] . '/' . $category['all_messages'] . ')'] = array(
                        'url' => array('edit', 'category' => $category['category'], 'new' => false, 'language' => $lang),
                        'active'=>isset($_GET['category'])&&$_GET['category']==$category['category']&&
                            isset($_GET['language'])&&$_GET['language']==$lang,
                    );
                }
                $cat['items'] = $items;
                $this->sidebarPages[$this->categories[$category['category']]['title']] = $cat;
            }

        list($this->sidebarTree, $ok) = $this->makeTree($this->sidebarPages);

        parent::init();
    }

    public $loadedCategories = array();

    public function actionAuto()
    {
        $models = SourceMessage::model()->findAll();
        foreach ($models as $model) {
            foreach (Yii::app()->params['languages'] as $lang) {
                $message = Message::model()->findAllByAttributes(array(
                    'id' => $model->id,
                    'language' => $lang,
                ));
                if ($message == null && $lang != 'ru') {
                    $message = new Message();
                    $message->id = $model->id;
                    $message->language = $lang;
                    $message->translation = $this->_translateString($model->message, 'ru', $lang);
                    if ($message->translation != '')
                        $message->save();
                }
            }
//            break;
        }
    }

    protected function _translateString($str, $from, $to)
    {
        $c = curl_init(
        //replace appId with your one
            "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=56224082C67582DF5178C7761F6034AA597D464D&text=" .
                urlencode($str) . "&from={$from}&to={$to}&contentType=" . urlencode('text/plain') . "&category=general");

        curl_setopt($c, CURL_HTTP_VERSION_1_1, 1);
        curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($c, CURLOPT_HEADER, 0);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_USERAGENT, 'Mozilla/5.0');

        $b = curl_exec($c);
        if (200 != curl_getinfo($c, CURLINFO_HTTP_CODE)) {
            echo('Ошибка подключения к Bing Translate [' . curl_getinfo($c, CURLINFO_HTTP_CODE) . ']. Перезапуск перевода.');
            return '';
            //$this->_translateString($str, $from, $to);
        }

        curl_close($c);

        $translate = mb_substr($b, 4, -1);
        echo("{$str} ($from -> $to) : $translate\n");

        return $translate;
    }


    /**
     * 'data' for CTreeView displayed in sidebar in treeSidebar layout
     * @var array
     */
    public $sidebarTree;

    /**
     * Generastes 'data' for CTreeView
     * @param $pages
     * @return list($data, $isActive)
     */
    private function makeTree($pages)
    {
        $res = array();
        $active = false;
        foreach ($pages as $nodeName => $node) {
            $itemActive = isset($node['active'])?$node['active']:false;
            $active = $active || $itemActive;
            $newOne = array(
                'text' => (isset($node['url'])
                    ? CHtml::link(
                        $nodeName,
                        $node['url'],
                        array('class' => ($itemActive) ? 'active' : ''))
                    : $nodeName),
            );

            if (isset($node['items']))
                list($newOne['children'], $newOne['expanded']) = $this->makeTree($node['items']);
            $res[] = $newOne;
        }
        return array($res, $active);
    }

}