<?php

/**
 * Description of SourceMessageHandler
 *
 * @author Mohammed Osman  <osmancode@gmail.com>
 */
class MessageSourceHandler {

    public static function onMissingTranslation($event) {

        $message = NULL;
        $attributes = array(
            'category' => $event->category,
            'message' => $event->message
        );
        $model = SourceMessage::model()->find('message=:message AND category=:category', $attributes);


        if ($model === NULL) {
            $model = new SourceMessage();
            $model->attributes = $attributes;
            if (!$model->save()) {
                return Yii::log('Message ' . $event->message . ' could not be added to SourceMessage table');
            }
        } else {
            // if the source message already inserted then we need to check for the message translation.
            $message = Message::model()->find('id=:id AND language=:language', array(
                'id' => $model->id,
                'language' => Yii::app()->language
            ));
        }

        if ($message === NULL) {
            $message = new Message();
            $message->id = $model->id;
            $message->translation = $model->message;
            $message->language = Yii::app()->language;

            if (!$message->save()) {
                return Yii::log('Message ' . $event->message . ' could not be added to Message table');
            }
        }
        return $event;
    }

    public static function saveToFiles() {

        $sql = "
        SELECT msg.language ,src.category,src.message,msg.translation
        FROM fmessage_locale as locale
        JOIN fmessage_message as msg
            ON msg.`language` = locale.locale
            AND locale.active = 1
        JOIN fmessage_sourcemessage as src
            ON src.id = msg.id";


        $rows = Yii::app()->db->createCommand($sql)->queryAll();












        $savePath = Yii::app()->basePath . '/messages';
        //create directories
        if (!is_dir($savePath)) {
            @mkdir($savePath);
        } else {
            $dirs = glob($savePath . "/*", GLOB_ONLYDIR);
            try {
                array_map('CFileHelper::removeDirectory', $dirs);
            } catch (Exception $exc) {
                return Yii::log($exc->getTraceAsString());
            }
        }

        $files = array();
        foreach ($rows as $row) {
            $key = $savePath . "/{$row['language']}/{$row['category']}.php";
            $files[$key][$row['message']] = $row['translation'];
        }

        foreach ($files as $key => $value) {
            $dirname = dirname($key);

            if (!is_dir($dirname)) {
                @mkdir($dirname);
            }
            
            
            file_put_contents($key, "<?php \r\nreturn " . var_export($value, true) . ";");
        }
    }

}
