<commit_before><?php
use MapasCulturais\App;

$app = App::i();

function is_editable() {
    return (bool) preg_match('#^\w+/(create|edit)$#', App::i()->view->template);
}

$app->hook('view.render(<<*>>):before', function() use($app) {
    $app->enqueueStyle('fonts', 'elegant', '/css/elegant-font.css');

    $app->enqueueStyle('vendor', 'select2', '/vendor/select2/select2.css');
    $app->enqueueStyle('vendor', 'x-editable', '/vendor/x-editable/jquery-editable/css/jquery-editable.css', array('select2'));
    $app->enqueueStyle('vendor', 'x-editable-tip', '/vendor/x-editable/jquery-editable/css/tip-yellowsimple.css', array('x-editable'));

    $app->enqueueStyle('app', 'style', '/css/style.css');

    $app->enqueueScript('vendor', 'mustache', '/vendor/mustache.js');
    $app->enqueueScript('vendor', 'jquery', '/vendor/jquery/jquery-2.0.3.min.js');
    $app->enqueueScript('vendor', 'jquery-slimscroll', '/vendor/jquery.slimscroll.min.js');
    $app->enqueueScript('vendor', 'jquery-form', '/vendor/jquery.form.min.js', array('jquery'));
    $app->enqueueScript('vendor', 'jquery-mask', '/vendor/jquery.mask.min.js', array('jquery'));
    $app->enqueueScript('vendor', 'purl', '/vendor/purl/purl.js', array('jquery'));

    $app->enqueueScript('app', 'tim', '/js/tim.js');
    $app->enqueueScript('app', 'mapasculturais', '/js/mapasculturais.js', array('tim'));

    $app->enqueueScript('vendor', 'select2', '/vendor/select2/select2.js', array('jquery'));
    $app->enqueueScript('vendor', 'select2-BR', '/js/select2_locale_pt-BR-edit.js', array('select2'));

    $app->enqueueScript('vendor', 'poshytip', '/vendor/x-editable/jquery-editable/js/jquery.poshytip.js', array('jquery'));
    $app->enqueueScript('vendor', 'x-editable', '/vendor/x-editable/jquery-editable/js/jquery-editable-poshytip.js', array('jquery', 'poshytip', 'select2'));
    $app->enqueueScript('app', 'editable', '/js/editable.js', array('mapasculturais'));

    if ($app->config('mode') == 'staging')
        $app->enqueueStyle('app', 'staging', '/css/staging.css', array('style'));
});

function add_map_assets() {
    $app = App::i();
    //Leaflet -a JavaScript library for mobile-friendly maps
    $app->enqueueStyle('vendor', 'leaflet', '/vendor/leaflet/lib/leaflet-0.7.2/leaflet.css');
    $app->enqueueScript('vendor', 'leaflet', '/vendor/leaflet/lib/leaflet-0.7.2/leaflet.js');
    //Leaflet Vector Layers
    $app->enqueueScript('vendor', 'leaflet-vector-layers', '/vendor/leaflet-vector-layers/dist/lvector.js', array('leaflet'));
    //Conjuntos de Marcadores
    $app->enqueueStyle('vendor', 'leaflet-marker-cluster', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.markercluster-0.4/dist/MarkerCluster.css', array('leaflet'));
    $app->enqueueStyle('vendor', 'leaflet-marker-cluster-d', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.markercluster-0.4/dist/MarkerCluster.Default.css', array('leaflet-marker-cluster'));
    $app->enqueueScript('vendor', 'leaflet-marker-cluster', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.markercluster-0.4/dist/leaflet.markercluster.js', array('leaflet'));
    //Controle de Full Screen
    $app->enqueueStyle('vendor', 'leaflet-fullscreen', '/vendor/leaflet/lib/leaflet-plugins/brunob-leaflet.fullscreen-06c4127/Control.FullScreen.css', array('leaflet'));
    $app->enqueueScript('vendor', 'leaflet-fullscreen', '/vendor/leaflet/lib/leaflet-plugins/brunob-leaflet.fullscreen-06c4127/Control.FullScreen.js', array('leaflet'));
    //Leaflet Label Plugin
    //$app->enqueueStyle( 'vendor', 'leaflet-label',           '/vendor/leaflet/lib/leaflet-plugins/leaflet-label/leaflet.label.css',                                         array('leaflet'));
    $app->enqueueScript('vendor', 'leaflet-label', '/vendor/leaflet/lib/leaflet-plugins/leaflet-label/leaflet.label.js', array('leaflet'));
    //Leaflet Draw
    $app->enqueueStyle('vendor', 'leaflet-draw', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.draw-0.2.3/dist/leaflet.draw.css', array('leaflet'));
    $app->enqueueScript('vendor', 'leaflet-draw', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.draw-0.2.3/dist/leaflet.draw.js', array('leaflet'));

    //Google Maps API. In dev mode, test internet connection to avoid waiting for host timeout when working without connection
    if ($app->config('mode') !== 'development' || @fsockopen("maps.google.com", 80))
        $app->enqueueScript('vendor', 'google-maps-api', 'http://maps.google.com/maps/api/js?v=3.2&sensor=false');

    //Leaflet Plugins (Google)false');
    $app->enqueueScript('vendor', 'leaflet-google-tile', '/vendor/leaflet/lib/leaflet-plugins/leaflet-plugins-master/layer/tile/Google.js', array('leaflet'));
    //Pure CSS Tooltips (Hint - https://github.com/chinchang/hint.css)
    //$app->enqueueStyle('vendor', 'hint', 'http://cdn.jsdelivr.net/hint.css/1.3.0/hint.min.css');
    //Mapa das Singles
    $app->enqueueStyle('app', 'map', '/css/map.css');
    $app->enqueueScript('app', 'map', '/js/map.js');
}

function add_angular_entity_assets($entity){
    $app = App::i();
    $app->enqueueScript('vendor', 'jquery-ui-position', '/vendor/jquery-ui.position.min.js', array('jquery'));

    $app->enqueueScript('vendor', 'angular', '/vendor/angular.js');
    $app->enqueueScript('vendor', 'angular-sanitize', '/vendor/angular-sanitize.min.js', array('angular'));
    $app->enqueueScript('vendor', 'spin.js', '/vendor/spin.min.js', array('angular'));
    $app->enqueueScript('vendor', 'angularSpinner', '/vendor/angular-spinner.min.js', array('spin.js'));

    $app->enqueueScript('app', 'ng-mapasculturais', '/js/ng-mapasculturais.js');
    $app->enqueueScript('app', 'related-agents', '/js/RelatedAgents.js');
    $app->enqueueScript('app', 'entity', '/js/Entity.js', array('mapasculturais', 'ng-mapasculturais', 'related-agents'));
    if(!is_editable())
        return;

    App::i()->hook('mapasculturais.scripts', function() use($app, $entity) {
        $isEntityOwner = $entity->ownerUser->id === $app->user->id;
        ?>
        <script type="text/javascript">
            MapasCulturais.entity = MapasCulturais.entity || {};
            MapasCulturais.entity.canUserCreateRelatedAgentsWithControl = <?php echo $entity->canUser('createAgentRelationWithControl') ? 'true' : 'false' ?>;
        </script>
        <?php
    });
}

function add_entity_properties_metadata_to_js($entity) {
    $class = $entity->className;
    $metadata = $class::getPropertiesMetadata();
    App::i()->hook('mapasculturais.scripts', function() use($metadata) {
        ?>
        <script type="text/javascript">
            MapasCulturais.Editables.entity = <?php echo json_encode($metadata); ?>;
        </script>
        <?php
    });
}

function getOccurrenceFrequencies() {
    return array(
        'once' => 'uma vez',
        'daily' => 'todos os dias',
        'weekly' => 'semanal',
        'monthly' => 'mensal',
    );
}

function add_occurrence_frequencies_to_js() {
    ?>
    <script type="text/javascript">
        MapasCulturais.frequencies = <?php echo json_encode(getOccurrenceFrequencies()); ?>;
    </script>
    <?php
}

function add_entity_types_to_js($entity) {
    App::i()->hook('mapasculturais.scripts', function() use($entity) {
        $controller = App::i()->getControllerByEntity($entity);
        $types = $controller->types;

        usort($types, function($a, $b) {
            if ($a->name > $b->name)
                return 1;
            elseif ($a->name < $b->name)
                return -1;
            else
                return 0;
        });
        ?>
        <script type="text/javascript">
            MapasCulturais.entityTypes = MapasCulturais.entityTypes || {};
            MapasCulturais.entityTypes.<?php echo $controller->id ?> = <?php echo json_encode($types); ?>
        </script>
        <?php
    });
}

function add_taxonoy_terms_to_js($taxonomy_slug) {
    $terms = App::i()->repo('Term')->getTermsAsString($taxonomy_slug);
    App::i()->hook('mapasculturais.scripts', function() use($taxonomy_slug, $terms) {
        ?>
        <script type="text/javascript">

            MapasCulturais.taxonomyTerms = MapasCulturais.taxonomyTerms || {};
            MapasCulturais.taxonomyTerms.<?php echo $taxonomy_slug ?> = <?php echo json_encode($terms); ?>
        </script>
        <?php
    });
}

function add_agent_relations_to_js($entity){
    App::i()->hook('mapasculturais.scripts', function() use($entity) {
        ?>
        <script type="text/javascript">
            MapasCulturais.entity = MapasCulturais.entity || {};
            MapasCulturais.entity.agentRelations = <?php echo json_encode($entity->getAgentRelationsGrouped()); ?>;
        </script>
        <?php
    });

}

/**
 *
 * @param type $file_owner
 * @param type $group_name
 * @param type $response_action
 * @param type $response_target
 * @param type $response_template
 * @param type $response_transform
 * @param type $add_description_input
 */
function add_ajax_uploader($file_owner, $group_name, $response_action, $response_target, $response_template = '', $response_transform = '', $add_description_input = false, $file_types = 'jpg ou png') {
    App::i()->view->part('parts/ajax-uploader', array(
        'file_owner' => $file_owner,
        'file_group' => $group_name,
        'response_action' => $response_action,
        'response_target' => $response_target,
        'response_template' => $response_template,
        'response_transform' => $response_transform,
        'add_description' => $add_description_input,
        'file_types' => $file_types
    ));
}

/**
 *
 * @param type $file_owner
 * @param type $group_name
 * @param type $response_action
 * @param type $response_target
 * @param type $response_template
 * @param type $response_transform
 * @param type $add_description_input1
 */
function add_metalist_manager($object, $metalist_group, $metalist_action, $response_action, $response_target, $response_template = '', $response_transform = '', $add_description_input = false) {

    App::i()->view->part('parts/metalist-manager', array(
        'object' => $object,
        'metalist_group' => $metalist_group,
        'metalist_action' => $metalist_action,
        'response_action' => $response_action,
        'response_target' => $response_target,
        'response_template' => $response_template,
        'response_transform' => $response_transform,
        'add_description' => $add_description_input
    ));
}

/*
  MapasCulturais\App::i()->hook('controller(agent).render(single)', function(&$template){
  $template = 'edit';

  });
 */


$app->hook('entity(<<agent|space>>).<<insert|update>>:before', function() use ($app) {

    $rsm = new \Doctrine\ORM\Query\ResultSetMapping();
    $rsm->addScalarResult('nome', 'nome');

    $x = $this->location->longitude;
    $y = $this->location->latitude;

    $whereContains = 'WHERE ST_Contains(the_geom, ST_Transform(ST_GeomFromText(\'POINT(' . $x . ' ' . $y . ')\',4326),4326))';

    $strNativeQuery = 'SELECT nome FROM "sp_regiao" ' . $whereContains;
    $query = $app->getEm()->createNativeQuery($strNativeQuery, $rsm);
    $this->sp_regiao = $query->getOneOrNullResult()['nome'];

    $strNativeQuery = 'SELECT nome FROM "sp_subprefeitura" ' . $whereContains;
    $query = $app->getEm()->createNativeQuery($strNativeQuery, $rsm);
    $this->sp_subprefeitura = $query->getOneOrNullResult()['nome'];

    $strNativeQuery = 'SELECT nome_distr AS nome FROM "sp_distrito" ' . $whereContains;
    $query = $app->getEm()->createNativeQuery($strNativeQuery, $rsm);
    $this->sp_distrito = $query->getOneOrNullResult()['nome'];
});

// sempre que insere uma imagem cria o avatarSmall
$app->hook('entity(<<agent|space|event|project>>).file(avatar).insert:after', function() {
    $this->transform('avatarSmall');
    $this->transform('avatarBig');
});

$app->hook('entity(<<agent|space|event|project>>).file(header).insert:after', function() {
    $this->transform('header');
});

$app->hook('entity(<<agent|space|event|project>>).file(gallery).insert:after', function() {
    $this->transform('galleryThumb');
    $this->transform('galleryFull');
});

$app->hook('entity(event).load', function() {
    $this->type = 1;
});

$app->hook('entity(event).save:before', function() {
    $this->type = 1;
});


//plugin Em Cartaz
// TODO: Mover arquivo de template de views/panel/em-cartaz.php para a pasta de plugins



$defaultFrom = new DateTime("first day of next month");
$defaultTo = new DateTime("last day of next month");

$app->hook('GET(panel.em-cartaz)', function() use ($app, $defaultFrom, $defaultTo) {
    $this->requireAuthentication();
    if(!$app->user->is('admin') && !$app->user->is('staff')){
        //throw new MapasCulturais\Exceptions\PermissionDenied;
        $app->pass();
    }
    $this->render('part-em-cartaz', array(
        'content'=>'',
        'from' => isset($this->getData['from']) ? new DateTime($this->getData['from']) : $defaultFrom,
        'to' => isset($this->getData['to']) ? new DateTime($this->getData['to']) : $defaultTo,
    ));
});

$app->hook('view.partial(panel/part-nav):after', function($template, &$html) use ($app){
    if(!$app->user->is('admin') && !$app->user->is('staff')){
        //throw new MapasCulturais\Exceptions\PermissionDenied;
        $app->pass();
    }
    $a_class = $this->template == 'panel/em-cartaz' ? 'active' : '';
    $url = $app->createUrl('panel', 'em-cartaz');
    $menu = "<li><a class='$a_class' href='$url'><span class='icone icon_document_alt'></span> Em Cartaz</a></li>";
    $html = str_replace('</ul>', $menu . '</ul>', $html);
});


$app->hook('GET(panel.em-cartaz-<<download|preview>>)', function() use ($app, $defaultFrom, $defaultTo) {
    if(!$app->user->is('admin') && !$app->user->is('staff')){
        //throw new MapasCulturais\Exceptions\PermissionDenied;
        $app->pass();
    }
    $from = isset($this->getData['from']) ? new DateTime($this->getData['from']) : $defaultFrom;
    $to = isset($this->getData['to']) ? new DateTime($this->getData['to']) : $defaultTo;


    $phpWord = new \PhpOffice\PhpWord\PhpWord();

    // Every element you want to append to the word document is placed in a section.
    // To create a basic section:
    $section = $phpWord->addSection();

    $defaultFont = $phpWord->addFontStyle('defaultFont',
        array('name'=>'Arial', 'size'=>12));

    $documentHead = $phpWord->addFontStyle('documentHead',
        array('name'=>'Arial', 'size'=>18, 'color'=>'44AA88', 'bold'=>true));

    $eventTitle = $phpWord->addFontStyle('eventTitle',
        array('name'=>'Arial', 'size'=>12, 'color'=>'880000', 'bold'=>true));

    $linguagemStyle = $phpWord->addFontStyle('linguagemStyle',
        array('name'=>'Arial', 'size'=>12, 'color'=>'FF0000', 'bold'=>true));

    $linguagens = array(
        'cinema', 'dança', 'teatro', 'música popular', 'música erudita', 'exposição', 'curso ou oficina', 'palestra, pebate ou encontro'
    );

    $section->addText('ROTEIRO GERAL (SITE) REVISTA', $documentHead);

    $addEventBlockHtml = function($event) use ($section, $defaultFont, $eventTitle){
        $textRunObj = $section->createTextRun();
        $textRunObj->addText($event['name'], $eventTitle);
        $textRunObj->addTextBreak();
        $spaces = array();
        $occurenceDescription = '';
        foreach($event['occurrences'] as $occurrence){
            if(isset($occurrence->rule->description)){
                $occurenceDescription .= $occurrence->rule->description.'. ';
            }
            if(isset($occurrence->rule->price)){
                $occurenceDescription .= $occurrence->rule->price.'. ';
            }
            if (!array_key_exists($occurrence->space->id, $spaces)){
                $spaces[$occurrence->space->id] = $occurrence->space;
            }
        }
        $spaceText = '';
        foreach($spaces as $space){
            $spaceText .= $space->name . ', '. $space->endereco.'. ';
        }
        $textRunObj->addText($event['shortDescription'].' '.$spaceText.$occurenceDescription, $defaultFont);
    };

    $addEventBlockDoc = function($event) use ($section, $defaultFont, $eventTitle){
        $section->addText('');
        $section->addText($event['name'], $eventTitle);
        //$section->addText($event['shortDescription'], $defaultFont);
        $spaces = array();
        $occurenceDescription = '';
        foreach($event['occurrences'] as $occurrence){
            if(isset($occurrence->rule->description)){
                $occurenceDescription .= trim($occurrence->rule->description).'. ';
            }
            if(isset($occurrence->rule->price)){
                $occurenceDescription .= trim($occurrence->rule->price).'. ';
            }
            if (!array_key_exists($occurrence->space->id, $spaces)){
                $spaces[$occurrence->space->id] = $occurrence->space;
            }
        }
        $spaceText = '';
        foreach($spaces as $space){
            $spaceText .= trim($space->name) . ', '. trim($space->endereco).'. ';
        }

        $section->addText(trim($event['shortDescription']).' '.trim($spaceText).' '.trim($occurenceDescription), $defaultFont);
    };


    foreach($linguagens as $linguagem){

        $query = array(
            'isVerified' => 'eq(true)',
            '@from'=>$from->format('Y-m-d'),
            '@to'=>$to->format('Y-m-d'),
            '@select' => 'id,name,shortDescription,location,metadata,occurrences,project',
            '@order' => 'name ASC',
            'term:linguagem'=>'ILIKE('.$linguagem.'*)'
        );

        $events = $app->controller('event')->apiQueryByLocation($query);

        $section->addText('');
        $section->addText('');
        $section->addText(mb_strtoupper($linguagem, 'UTF-8').'*', $linguagemStyle);

        $projects = array();

        foreach($events as $event){
            if($event['project']){
                if(!isset($projects[$event['project']->id])){<commit_msg>Em Cartaz related agents group and name (refs #225)<commit_after><?php
use MapasCulturais\App;

$app = App::i();

function is_editable() {
    return (bool) preg_match('#^\w+/(create|edit)$#', App::i()->view->template);
}

$app->hook('view.render(<<*>>):before', function() use($app) {
    $app->enqueueStyle('fonts', 'elegant', '/css/elegant-font.css');

    $app->enqueueStyle('vendor', 'select2', '/vendor/select2/select2.css');
    $app->enqueueStyle('vendor', 'x-editable', '/vendor/x-editable/jquery-editable/css/jquery-editable.css', array('select2'));
    $app->enqueueStyle('vendor', 'x-editable-tip', '/vendor/x-editable/jquery-editable/css/tip-yellowsimple.css', array('x-editable'));

    $app->enqueueStyle('app', 'style', '/css/style.css');

    $app->enqueueScript('vendor', 'mustache', '/vendor/mustache.js');
    $app->enqueueScript('vendor', 'jquery', '/vendor/jquery/jquery-2.0.3.min.js');
    $app->enqueueScript('vendor', 'jquery-slimscroll', '/vendor/jquery.slimscroll.min.js');
    $app->enqueueScript('vendor', 'jquery-form', '/vendor/jquery.form.min.js', array('jquery'));
    $app->enqueueScript('vendor', 'jquery-mask', '/vendor/jquery.mask.min.js', array('jquery'));
    $app->enqueueScript('vendor', 'purl', '/vendor/purl/purl.js', array('jquery'));

    $app->enqueueScript('app', 'tim', '/js/tim.js');
    $app->enqueueScript('app', 'mapasculturais', '/js/mapasculturais.js', array('tim'));

    $app->enqueueScript('vendor', 'select2', '/vendor/select2/select2.js', array('jquery'));
    $app->enqueueScript('vendor', 'select2-BR', '/js/select2_locale_pt-BR-edit.js', array('select2'));

    $app->enqueueScript('vendor', 'poshytip', '/vendor/x-editable/jquery-editable/js/jquery.poshytip.js', array('jquery'));
    $app->enqueueScript('vendor', 'x-editable', '/vendor/x-editable/jquery-editable/js/jquery-editable-poshytip.js', array('jquery', 'poshytip', 'select2'));
    $app->enqueueScript('app', 'editable', '/js/editable.js', array('mapasculturais'));

    if ($app->config('mode') == 'staging')
        $app->enqueueStyle('app', 'staging', '/css/staging.css', array('style'));
});

function add_map_assets() {
    $app = App::i();
    //Leaflet -a JavaScript library for mobile-friendly maps
    $app->enqueueStyle('vendor', 'leaflet', '/vendor/leaflet/lib/leaflet-0.7.2/leaflet.css');
    $app->enqueueScript('vendor', 'leaflet', '/vendor/leaflet/lib/leaflet-0.7.2/leaflet.js');
    //Leaflet Vector Layers
    $app->enqueueScript('vendor', 'leaflet-vector-layers', '/vendor/leaflet-vector-layers/dist/lvector.js', array('leaflet'));
    //Conjuntos de Marcadores
    $app->enqueueStyle('vendor', 'leaflet-marker-cluster', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.markercluster-0.4/dist/MarkerCluster.css', array('leaflet'));
    $app->enqueueStyle('vendor', 'leaflet-marker-cluster-d', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.markercluster-0.4/dist/MarkerCluster.Default.css', array('leaflet-marker-cluster'));
    $app->enqueueScript('vendor', 'leaflet-marker-cluster', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.markercluster-0.4/dist/leaflet.markercluster.js', array('leaflet'));
    //Controle de Full Screen
    $app->enqueueStyle('vendor', 'leaflet-fullscreen', '/vendor/leaflet/lib/leaflet-plugins/brunob-leaflet.fullscreen-06c4127/Control.FullScreen.css', array('leaflet'));
    $app->enqueueScript('vendor', 'leaflet-fullscreen', '/vendor/leaflet/lib/leaflet-plugins/brunob-leaflet.fullscreen-06c4127/Control.FullScreen.js', array('leaflet'));
    //Leaflet Label Plugin
    //$app->enqueueStyle( 'vendor', 'leaflet-label',           '/vendor/leaflet/lib/leaflet-plugins/leaflet-label/leaflet.label.css',                                         array('leaflet'));
    $app->enqueueScript('vendor', 'leaflet-label', '/vendor/leaflet/lib/leaflet-plugins/leaflet-label/leaflet.label.js', array('leaflet'));
    //Leaflet Draw
    $app->enqueueStyle('vendor', 'leaflet-draw', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.draw-0.2.3/dist/leaflet.draw.css', array('leaflet'));
    $app->enqueueScript('vendor', 'leaflet-draw', '/vendor/leaflet/lib/leaflet-plugins/Leaflet.draw-0.2.3/dist/leaflet.draw.js', array('leaflet'));

    //Google Maps API. In dev mode, test internet connection to avoid waiting for host timeout when working without connection
    if ($app->config('mode') !== 'development' || @fsockopen("maps.google.com", 80))
        $app->enqueueScript('vendor', 'google-maps-api', 'http://maps.google.com/maps/api/js?v=3.2&sensor=false');

    //Leaflet Plugins (Google)false');
    $app->enqueueScript('vendor', 'leaflet-google-tile', '/vendor/leaflet/lib/leaflet-plugins/leaflet-plugins-master/layer/tile/Google.js', array('leaflet'));
    //Pure CSS Tooltips (Hint - https://github.com/chinchang/hint.css)
    //$app->enqueueStyle('vendor', 'hint', 'http://cdn.jsdelivr.net/hint.css/1.3.0/hint.min.css');
    //Mapa das Singles
    $app->enqueueStyle('app', 'map', '/css/map.css');
    $app->enqueueScript('app', 'map', '/js/map.js');
}

function add_angular_entity_assets($entity){
    $app = App::i();
    $app->enqueueScript('vendor', 'jquery-ui-position', '/vendor/jquery-ui.position.min.js', array('jquery'));

    $app->enqueueScript('vendor', 'angular', '/vendor/angular.js');
    $app->enqueueScript('vendor', 'angular-sanitize', '/vendor/angular-sanitize.min.js', array('angular'));
    $app->enqueueScript('vendor', 'spin.js', '/vendor/spin.min.js', array('angular'));
    $app->enqueueScript('vendor', 'angularSpinner', '/vendor/angular-spinner.min.js', array('spin.js'));

    $app->enqueueScript('app', 'ng-mapasculturais', '/js/ng-mapasculturais.js');
    $app->enqueueScript('app', 'related-agents', '/js/RelatedAgents.js');
    $app->enqueueScript('app', 'entity', '/js/Entity.js', array('mapasculturais', 'ng-mapasculturais', 'related-agents'));
    if(!is_editable())
        return;

    App::i()->hook('mapasculturais.scripts', function() use($app, $entity) {
        $isEntityOwner = $entity->ownerUser->id === $app->user->id;
        ?>
        <script type="text/javascript">
            MapasCulturais.entity = MapasCulturais.entity || {};
            MapasCulturais.entity.canUserCreateRelatedAgentsWithControl = <?php echo $entity->canUser('createAgentRelationWithControl') ? 'true' : 'false' ?>;
        </script>
        <?php
    });
}

function add_entity_properties_metadata_to_js($entity) {
    $class = $entity->className;
    $metadata = $class::getPropertiesMetadata();
    App::i()->hook('mapasculturais.scripts', function() use($metadata) {
        ?>
        <script type="text/javascript">
            MapasCulturais.Editables.entity = <?php echo json_encode($metadata); ?>;
        </script>
        <?php
    });
}

function getOccurrenceFrequencies() {
    return array(
        'once' => 'uma vez',
        'daily' => 'todos os dias',
        'weekly' => 'semanal',
        'monthly' => 'mensal',
    );
}

function add_occurrence_frequencies_to_js() {
    ?>
    <script type="text/javascript">
        MapasCulturais.frequencies = <?php echo json_encode(getOccurrenceFrequencies()); ?>;
    </script>
    <?php
}

function add_entity_types_to_js($entity) {
    App::i()->hook('mapasculturais.scripts', function() use($entity) {
        $controller = App::i()->getControllerByEntity($entity);
        $types = $controller->types;

        usort($types, function($a, $b) {
            if ($a->name > $b->name)
                return 1;
            elseif ($a->name < $b->name)
                return -1;
            else
                return 0;
        });
        ?>
        <script type="text/javascript">
            MapasCulturais.entityTypes = MapasCulturais.entityTypes || {};
            MapasCulturais.entityTypes.<?php echo $controller->id ?> = <?php echo json_encode($types); ?>
        </script>
        <?php
    });
}

function add_taxonoy_terms_to_js($taxonomy_slug) {
    $terms = App::i()->repo('Term')->getTermsAsString($taxonomy_slug);
    App::i()->hook('mapasculturais.scripts', function() use($taxonomy_slug, $terms) {
        ?>
        <script type="text/javascript">

            MapasCulturais.taxonomyTerms = MapasCulturais.taxonomyTerms || {};
            MapasCulturais.taxonomyTerms.<?php echo $taxonomy_slug ?> = <?php echo json_encode($terms); ?>
        </script>
        <?php
    });
}

function add_agent_relations_to_js($entity){
    App::i()->hook('mapasculturais.scripts', function() use($entity) {
        ?>
        <script type="text/javascript">
            MapasCulturais.entity = MapasCulturais.entity || {};
            MapasCulturais.entity.agentRelations = <?php echo json_encode($entity->getAgentRelationsGrouped()); ?>;
        </script>
        <?php
    });

}

/**
 *
 * @param type $file_owner
 * @param type $group_name
 * @param type $response_action
 * @param type $response_target
 * @param type $response_template
 * @param type $response_transform
 * @param type $add_description_input
 */
function add_ajax_uploader($file_owner, $group_name, $response_action, $response_target, $response_template = '', $response_transform = '', $add_description_input = false, $file_types = 'jpg ou png') {
    App::i()->view->part('parts/ajax-uploader', array(
        'file_owner' => $file_owner,
        'file_group' => $group_name,
        'response_action' => $response_action,
        'response_target' => $response_target,
        'response_template' => $response_template,
        'response_transform' => $response_transform,
        'add_description' => $add_description_input,
        'file_types' => $file_types
    ));
}

/**
 *
 * @param type $file_owner
 * @param type $group_name
 * @param type $response_action
 * @param type $response_target
 * @param type $response_template
 * @param type $response_transform
 * @param type $add_description_input1
 */
function add_metalist_manager($object, $metalist_group, $metalist_action, $response_action, $response_target, $response_template = '', $response_transform = '', $add_description_input = false) {

    App::i()->view->part('parts/metalist-manager', array(
        'object' => $object,
        'metalist_group' => $metalist_group,
        'metalist_action' => $metalist_action,
        'response_action' => $response_action,
        'response_target' => $response_target,
        'response_template' => $response_template,
        'response_transform' => $response_transform,
        'add_description' => $add_description_input
    ));
}

/*
  MapasCulturais\App::i()->hook('controller(agent).render(single)', function(&$template){
  $template = 'edit';

  });
 */


$app->hook('entity(<<agent|space>>).<<insert|update>>:before', function() use ($app) {

    $rsm = new \Doctrine\ORM\Query\ResultSetMapping();
    $rsm->addScalarResult('nome', 'nome');

    $x = $this->location->longitude;
    $y = $this->location->latitude;

    $whereContains = 'WHERE ST_Contains(the_geom, ST_Transform(ST_GeomFromText(\'POINT(' . $x . ' ' . $y . ')\',4326),4326))';

    $strNativeQuery = 'SELECT nome FROM "sp_regiao" ' . $whereContains;
    $query = $app->getEm()->createNativeQuery($strNativeQuery, $rsm);
    $this->sp_regiao = $query->getOneOrNullResult()['nome'];

    $strNativeQuery = 'SELECT nome FROM "sp_subprefeitura" ' . $whereContains;
    $query = $app->getEm()->createNativeQuery($strNativeQuery, $rsm);
    $this->sp_subprefeitura = $query->getOneOrNullResult()['nome'];

    $strNativeQuery = 'SELECT nome_distr AS nome FROM "sp_distrito" ' . $whereContains;
    $query = $app->getEm()->createNativeQuery($strNativeQuery, $rsm);
    $this->sp_distrito = $query->getOneOrNullResult()['nome'];
});

// sempre que insere uma imagem cria o avatarSmall
$app->hook('entity(<<agent|space|event|project>>).file(avatar).insert:after', function() {
    $this->transform('avatarSmall');
    $this->transform('avatarBig');
});

$app->hook('entity(<<agent|space|event|project>>).file(header).insert:after', function() {
    $this->transform('header');
});

$app->hook('entity(<<agent|space|event|project>>).file(gallery).insert:after', function() {
    $this->transform('galleryThumb');
    $this->transform('galleryFull');
});

$app->hook('entity(event).load', function() {
    $this->type = 1;
});

$app->hook('entity(event).save:before', function() {
    $this->type = 1;
});


//plugin Em Cartaz
// TODO: Mover arquivo de template de views/panel/part-em-cartaz.php para a pasta de plugins

$defaultFrom = new DateTime("first day of next month");
$defaultTo = new DateTime("last day of next month");

$app->hook('GET(panel.em-cartaz)', function() use ($app, $defaultFrom, $defaultTo) {
    $this->requireAuthentication();
    if(!$app->user->is('admin') && !$app->user->is('staff')){
        //throw new MapasCulturais\Exceptions\PermissionDenied;
        $app->pass();
    }
    $this->render('part-em-cartaz', array(
        'content'=>'',
        'from' => isset($this->getData['from']) ? new DateTime($this->getData['from']) : $defaultFrom,
        'to' => isset($this->getData['to']) ? new DateTime($this->getData['to']) : $defaultTo,
    ));
});

$app->hook('view.partial(panel/part-nav):after', function($template, &$html) use ($app){
    if(!$app->user->is('admin') && !$app->user->is('staff')){
        //throw new MapasCulturais\Exceptions\PermissionDenied;
        $app->pass();
    }
    $a_class = $this->template == 'panel/em-cartaz' ? 'active' : '';
    $url = $app->createUrl('panel', 'em-cartaz');
    $menu = "<li><a class='$a_class' href='$url'><span class='icone icon_document_alt'></span> Em Cartaz</a></li>";
    $html = str_replace('</ul>', $menu . '</ul>', $html);
});


$app->hook('GET(panel.em-cartaz-<<download|preview>>)', function() use ($app, $defaultFrom, $defaultTo) {
    if(!$app->user->is('admin') && !$app->user->is('staff')){
        //throw new MapasCulturais\Exceptions\PermissionDenied;
        $app->pass();
    }
    $from = isset($this->getData['from']) ? new DateTime($this->getData['from']) : $defaultFrom;
    $to = isset($this->getData['to']) ? new DateTime($this->getData['to']) : $defaultTo;


    $phpWord = new \PhpOffice\PhpWord\PhpWord();

    // Every element you want to append to the word document is placed in a section.
    // To create a basic section:
    $section = $phpWord->addSection();

    $defaultFont = $phpWord->addFontStyle('defaultFont',
        array('name'=>'Arial', 'size'=>12));

    $documentHead = $phpWord->addFontStyle('documentHead',
        array('name'=>'Arial', 'size'=>18, 'color'=>'44AA88', 'bold'=>true));

    $eventTitle = $phpWord->addFontStyle('eventTitle',
        array('name'=>'Arial', 'size'=>12, 'color'=>'880000', 'bold'=>true));

    $linguagemStyle = $phpWord->addFontStyle('linguagemStyle',
        array('name'=>'Arial', 'size'=>12, 'color'=>'FF0000', 'bold'=>true));

    $linguagens = array(
        'cinema', 'dança', 'teatro', 'música popular', 'música erudita', 'exposição', 'curso ou oficina', 'palestra, pebate ou encontro'
    );

    $section->addText('ROTEIRO GERAL (SITE) REVISTA', $documentHead);

    $addEventBlockHtml = function($event) use ($section, $defaultFont, $eventTitle){
        $textRunObj = $section->createTextRun();
        $textRunObj->addText($event['name'], $eventTitle);
        $textRunObj->addTextBreak();
        $spaces = array();
        $occurenceDescription = '';
        foreach($event['occurrences'] as $occurrence){
            if(isset($occurrence->rule->description)){
                $occurenceDescription .= $occurrence->rule->description.'. ';
            }
            if(isset($occurrence->rule->price)){
                $occurenceDescription .= $occurrence->rule->price.'. ';
            }
            if (!array_key_exists($occurrence->space->id, $spaces)){
                $spaces[$occurrence->space->id] = $occurrence->space;
            }
        }
        $spaceText = '';
        foreach($spaces as $space){
            $spaceText .= $space->name . ', '. $space->endereco.'. ';
        }
        $agentText = '';
        foreach($event['relatedAgents'] as $group=>$relatedAgent){
            $agentText .= $group.': ';
            foreach($relatedAgent as $agent){
                $agentText .= $agent->name.', ';
            }
        }

        $textRunObj->addText($event['shortDescription'].' '.$agentText.' '.$spaceText.$occurenceDescription, $defaultFont);
    };

    $addEventBlockDoc = function($event) use ($section, $defaultFont, $eventTitle){
        $section->addText('');
        $section->addText($event['name'], $eventTitle);
        //$section->addText($event['shortDescription'], $defaultFont);
        $spaces = array();
        $occurenceDescription = '';
        foreach($event['occurrences'] as $occurrence){
            if(isset($occurrence->rule->description)){
                $occurenceDescription .= trim($occurrence->rule->description).'. ';
            }
            if(isset($occurrence->rule->price)){
                $occurenceDescription .= trim($occurrence->rule->price).'. ';
            }
            if (!array_key_exists($occurrence->space->id, $spaces)){
                $spaces[$occurrence->space->id] = $occurrence->space;
            }
        }
        $spaceText = '';
        foreach($spaces as $space){
            $spaceText .= trim($space->name) . ', '. trim($space->endereco).'. ';
        }
        $agentText = '';
        foreach($event['relatedAgents'] as $group=>$relatedAgent){
            $agentText .= trim($group).': ';
            foreach($relatedAgent as $agent){
                $agentText .= ($agent->name).', ';
            }
        }

        $section->addText(trim($event['shortDescription']).'. '.trim($agentText).' '.trim($spaceText).' '.trim($occurenceDescription), $defaultFont);
    };


    foreach($linguagens as $linguagem){

        $query = array(
            'isVerified' => 'eq(true)',
            '@from'=>$from->format('Y-m-d'),
            '@to'=>$to->format('Y-m-d'),
            '@select' => 'id,name,shortDescription,location,metadata,occurrences,project,relatedAgents',
            '@order' => 'name ASC',
            'term:linguagem'=>'ILIKE('.$linguagem.'*)'
        );

        $events = $app->controller('event')->apiQueryByLocation($query);

        $section->addText('');
        $section->addText('');
        $section->addText(mb_strtoupper($linguagem, 'UTF-8').'*', $linguagemStyle);

        $projects = array();

        foreach($events as $event){
            if($event['project']){
                if(!isset($projects[$event['project']->id])){
{'fraction_non_alphanumeric': 0.20041157909178214, 'fraction_numerical': 0.004911510495266841, 'mean_word_length': 3.6169242462629847, 'pattern_counts': {'":': 0, '<': 103, '<?xml version=': 0, '>': 565, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '365406', 'n_tokens_mistral': 11901, 'n_tokens_neox': 11745, 'n_words': 1735}