<?php

/**
 * Implements hook_menu().
 */
function mkbh_map_page_menu()
{
    return [
        'kort' => [
            'title' => 'Map',
            'access callback' => TRUE,
            'page callback' => 'mkbh_map_page_content',
        ],
        'map/get-carousel-items' => [
            'access callback' => TRUE,
            'page callback' => 'mkbh_map_page_get_carousel_items',
            'delivery callback' => 'ajax_deliver',
            'type' => MENU_CALLBACK,
        ],
        'map/get-marker-popup/%' => [
            'access callback' => TRUE,
            'page callback' => 'mkbh_map_page_get_marker_popup',
            'page arguments' => [2],
            'delivery callback' => 'ajax_deliver',
            'type' => MENU_CALLBACK,
        ],
    ];
}

/**
 * Implements hook_theme().
 */
function mkbh_map_page_theme($existing, $type, $theme, $path)
{
    return [
        'mkbh_map_page' => [
            'variables' => [],
            'path' => $path . '/templates',
            'template' => 'mkbh-map-page',
        ],
        'mkbh_map_page_popup' => [
            'variables' => ['items' => NULL],
            'path' => $path . '/templates',
            'template' => 'mkbh-map-page-popup',
        ],
    ];
}

/**
 * Page callback for map page.
 */
function mkbh_map_page_content()
{
    $default_markers = _mkbh_map_page_init_markers();
    return [
        '#theme' => 'mkbh_map_page',
        '#attached' => [
            'js' => [
                drupal_get_path('module', 'mkbh_map_page') . '/js/map.js',
                libraries_get_path('bxslider') . '/jquery.bxslider.js',
                libraries_get_path('bxslider') . '/jquery.fitvids.js',
                drupal_get_path('module', 'mkbh_video_player') . '/assets/javascripts/flowplayer.js',
                drupal_get_path('module', 'mkbh_video_player') . '/assets/plugins/flowplayer/flowplayer.min.js',
                libraries_get_path('leaflet') . '/leaflet.js',
                libraries_get_path('leaflet') . '/Leaflet.fullscreen.js',
                libraries_get_path('isMobile') . '/isMobile.js',
                [
                    'data' => ['cover_map_default' => $default_markers],
                    'type' => 'setting',
                ],
            ],
            'css' => [
                libraries_get_path('bxslider') . '/jquery.bxslider.css',
                libraries_get_path('leaflet') . '/leaflet.css',
                libraries_get_path('leaflet') . '/leaflet.fullscreen.css',
                drupal_get_path('module', 'mkbh_video_player') . '/assets/less/flowplayer.less',
                drupal_get_path('module', 'mkbh_video_player') . '/assets/plugins/flowplayer/skin/minimalist.css',

            ],
        ],
    ];
}

/**
 * Get default markers.
 */
function _mkbh_map_page_init_markers()
{
    $items = [];

    $query = new EntityFieldQuery();

    $locationsSubQuery = db_select('location');
    $locationsSubQuery->addField('location', 'lid');

    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', ['article', 'vision', 'projekt', 'photo_series'])
        ->propertyCondition('status', NODE_PUBLISHED)
        ->addTag('mkbh_map_page_query_tag_node_has_location');

    $result = $query->execute();

    if (isset($result['node'])) {
        $nodeIds = array_keys($result['node']);
        $nodes = entity_load('node', $nodeIds);

        foreach ($nodes as $node) {
            if ($node->type == 'article') {
                $nw = entity_metadata_wrapper('node', $node->nid);
                $lang_leaser = $nw->field_article_lang_laeser->raw();

                if ($lang_leaser) {
                    $type = 'lang-laeser';
                } else {
                    $article_type_mapping = [
                        '5' => 'byens-rum',
                        '6' => 'byens-liv',
                        '7' => 'sponsoreret',
                        '8' => 'opinion',
                    ];
                    $article_type = $nw->field_article_type->raw();
                    $type = $article_type_mapping[$article_type];
                }
            } else {
                $type = $node->type;
            }
            if ($type == 'photo_series') {
                $foto[] = $node->nid;
            }

            if (!empty($node->location['latitude']) && !empty($node->location['longitude'])) {
                $items[$node->nid] = [
                    'nid' => $node->nid,
                    'latLng' => [
                        $node->location['latitude'],
                        $node->location['longitude'],
                    ],
                    'type' => $type,
                ];
            }
        }
    }

    return array_values($items);
}

function mkbh_map_page_query_mkbh_map_page_query_tag_node_has_location_alter(QueryAlterableInterface $query)
{
    $query->innerJoin('location_instance', 'l', 'l.nid = node.nid');
    $query->isNotNull('l.lid');
    $query->addField('l', 'lid');
}

/**
 * Return output for carousel.
 */
function mkbh_map_page_get_carousel_items()
{

    $markers = isset($_POST['markers']) ? $_POST['markers'] : [];

    $data = '';
    if ($markers) {
        if (count($markers) > 50) {
            array_splice($markers, 50);
        }
        foreach ($markers as $marker) {
            $item = mkbh_map_page_carousel_renderable_item($marker);

            $data .= render($item);
        }
    }

    print json_encode($data);
    drupal_exit();
}

/**
 * Render single carousel item.
 */
function mkbh_map_page_carousel_renderable_item($nid)
{
    $nw = entity_metadata_wrapper('node', $nid);
    $boundle = $nw->getBundle();
    switch ($boundle) {
        case 'article':
            $lang_leaser = $nw->field_article_lang_laeser->raw();
            if ($lang_leaser) {
                $type = 'lang-laeser';
            } else {
                $article_type_mapping = [
                    '5' => 'byens-rum',
                    '6' => 'byens-liv',
                    '7' => 'sponsoreret',
                    '8' => 'opinion',
                ];
                $article_type = $nw->field_article_type->raw();
                $type = $article_type_mapping[$article_type];
            }
            $mainTitle = $nw->title->raw();
            $subtitle = $nw->field_article_sub_headline->raw();
            if ($subtitle) {
                $title = "<span class='subtitle'>$subtitle</span><span class='separator'>&nbsp;/&nbsp;</span><span class='title'>$mainTitle</span>";
            } else {
                $title = "<span class='title'>$mainTitle</span>";
            }
            $districtObj = $nw->field_article_city_district->value();
            $district = $districtObj->name;
            break;
        case 'projekt':
            $title = '<span class="title">' . $nw->title->raw() . '</span>';
            $type = $boundle;
            $districtObj = $nw->field_project_city_district->value();
            $district = $districtObj->name;
            break;
        case 'photo_series':
            $type = $boundle;
            $title = '<span class="title">' . $nw->title->raw() . '</span>';
            $districtObj = $nw->field_photo_city_district->value();
            $district = $districtObj->name;
            break;
        case 'vision':
            $type = $boundle;
            $mainTitle = $nw->title->raw();
            $subtitle = $nw->field_article_sub_headline->raw();
            if ($subtitle) {
                $title = "<span class='subtitle'>$subtitle</span><span class='separator'>&nbsp;/&nbsp;</span><span class='title'>$mainTitle</span>";
            } else {
                $title = "<span class='title'>$mainTitle</span>";
            }
            $districtObj = $nw->field_article_city_district->value();
            $district = $districtObj->name;
            break;
        case 'you_write':
            $type = $boundle;
            $mainTitle = $nw->title->raw();
            $subtitle = $nw->field_write_sub_headline->raw();
            if ($subtitle) {
                $title = "<span class='subtitle'>$subtitle</span><span class='separator'>&nbsp;/&nbsp;</span><span class='title'>$mainTitle</span>";
            } else {
                $title = "<span class='title'>$mainTitle</span>";
            }
            $districtObj = $nw->field_write_city_district->value();
            $district = $districtObj->name;
            break;
    }

    $adapter = new Drupal\mkbh_blocks\Adapter\NodeAdapterProxy($nw->value());

    return [
        '#type' => 'container',
        '#attributes' => [
            'class' => ['single-item-info'],
            'data-nid' => $nid,
        ],
        $adapter->getRenderableMainImage('map_carousel'),
        [
            '#type' => 'container',
            '#attributes' => [
                'class' => ['item-text-info'],
            ],
            [
                '#theme' => 'html_tag',
                '#tag' => 'div',
                '#attributes' => [
                    'class' => ['item-city item-type-' . $type],
                ],
                '#value' => $district,
            ],
            [
                '#theme' => 'html_tag',
                '#tag' => 'div',
                '#attributes' => [
                    'class' => ['item-title'],
                ],
                '#value' => $title,
            ],
        ],
    ];
}

/**
 * Get renderable popup for marker.
 */
function mkbh_map_page_get_marker_popup($nid)
{
    $items = [];
    $nw = entity_metadata_wrapper('node', $nid);
    if ($nw->value()) {
        if ($nw->getBundle() == 'article') {
            $lang_leaser = $nw->field_article_lang_laeser->raw();
            if ($lang_leaser) {
                $type = 'lang-laeser';
            } else {
                $article_type_mapping = [
                    '5' => 'byens-rum',
                    '6' => 'byens-liv',
                    '7' => 'sponsoreret',
                    '8' => 'opinion',
                ];
                $article_type = $nw->field_article_type->raw();
                $type = $article_type_mapping[$article_type];
                $classType = $article_type_mapping[$article_type];
            }

            $district_field = 'field_article_city_district';
        } else {
            $nodeType = $nw->getBundle();
            switch ($nodeType) {
                case 'projekt';
                    $type = 'projekter';
                    $district_field = 'field_project_city_district';
                    $classType = $nodeType;
                    break;
                case 'photo_series';
                    $type = 'foto';
                    $district_field = 'field_photo_city_district';
                    $classType = $nodeType;;
                    break;
                case 'vision';
                    $type = 'visioner';
                    $district_field = 'field_article_city_district';
                    $classType = $nodeType;;
                    break;
                case 'you_write';
                    $type = 'du skriver';
                    $district_field = 'field_write_city_district';
                    $classType = $nodeType;;
                    break;
            }
        }

        $breadcrumbs_items = [];
        if (!empty($type)) {
            $breadcrumbs_items[] = [
                'data' => $type,
                'class' => ['item-city node-type item-type-' . $classType],
            ];
        }
        $district = $nw->$district_field->value();
        if (!is_null($district)) {
            $breadcrumbs_items[] = [
                'data' => $district->name,
                'class' => ['node-location'],
            ];
        }

        $breadcrumbs = [
            '#theme' => 'item_list',
            '#items' => $breadcrumbs_items,
        ];

        /** @var \Drupal\mkbh_blocks\Adapter\NodeAdapterInterface $adapter */
        $adapter = new Drupal\mkbh_blocks\Adapter\NodeAdapterProxy($nw->value());

        if ($nw->__isset('field_underrubrik')) {
            $subtitle = $nw->field_underrubrik->value();
        }

        $title = $adapter->getRenderableMainTitle(TRUE);
        $mainImage = $adapter->getRenderableMainImage('map_popup', TRUE);

        $items = [
            'main_image' => render($mainImage),
            'breadcrumbs' => render($breadcrumbs),
            'title' => render($title),
            'subtitle' => empty($subtitle) ? '' : $subtitle['value'],
            'date' => format_date($nw->created->raw(), 'mkbh_short'),
        ];
    }

    $return = [
        '#theme' => 'mkbh_map_page_popup',
        '#items' => $items,
    ];
    print json_encode([
        'html' => render($return),
        'lat' => $nw->value()->location['latitude'],
        'lng' => $nw->value()->location['longitude'],
    ]);
    drupal_exit();
}
