<?php

use Fisharebest\Webtrees\Http\RequestHandlers\MapDataList;
use Fisharebest\Webtrees\Http\RequestHandlers\MapDataSave;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\PlaceLocation;
use Fisharebest\Webtrees\View;

/**
 * @var array<string,string> $breadcrumbs
 * @var string               $latitude
 * @var string               $longitude
 * @var PlaceLocation        $location
 * @var array<array<float>>  $map_bounds
 * @var array<float>         $marker_position
 * @var PlaceLocation        $parent
 * @var mixed                $provider
 * @var string               $title
 */

?>

<?= view('components/breadcrumbs', ['links' => $breadcrumbs]) ?>

<h1><?= $title ?></h1>

<div class="form-group row">
    <div class="col-sm-12">
        <div id="osm-map" class="wt-ajax-load col-sm-12 osm-admin-map" dir="ltr"></div>
    </div>
</div>

<form method="post" action="<?= e(route(MapDataSave::class)) ?>">
    <?= csrf_field() ?>
    <input type="hidden" name="place_id" value="<?= e($location->id()) ?>">
    <input type="hidden" name="parent_id" value="<?= e($location->parent()->id()) ?>">

    <div class="form-group row">
        <label class="col-form-label col-sm-1" for="new_place_name">
            <?= I18N::translate('Place') ?>
        </label>
        <div class="col-sm-3">
            <input type="text" id="new_place_name" name="new_place_name" value="<?= e($location->locationName()) ?>" class="form-control" required="required" maxlength="120" pattern="[^,]+" dir="auto">
        </div>
    </div>

    <div class="form-group row">
        <label class="col-form-label col-sm-1" for="new_place_lati">
            <?= I18N::translate('Latitude') ?>
        </label>
        <div class="col-sm-3">
            <div class="input-group">
                <input type="text" dir="ltr" id="new_place_lati" class="editable form-control" name="new_place_lati" placeholder="<?= I18N::translate('degrees') ?>" value="<?= e($latitude) ?>">
            </div>
        </div>
    </div>

    <div class="form-group row">
        <label class="col-form-label col-sm-1" for="new_place_long">
            <?= I18N::translate('Longitude') ?>
        </label>
        <div class="col-sm-3">
            <div class="input-group">
                <input type="text" dir="ltr" id="new_place_long" class="editable form-control" name="new_place_long" placeholder="<?= I18N::translate('degrees') ?>" value="<?= e($longitude) ?>">
            </div>
        </div>
    </div>

    <div class="form-group row">
        <div class="col-sm-10 offset-sm-1">
            <button class="btn btn-primary" type="submit">
                <?= /* I18N: A button label. */
                I18N::translate('save')
                ?>
            </button>
            <a class="btn btn-secondary" href="<?= e(route(MapDataList::class, ['parent_id' => $parent->id()])) ?>">
                <?= I18N::translate('cancel') ?>
            </a>
        </div>
    </div>
</form>

<?php View::push('styles') ?>
<style>
    .osm-admin-map {
        height: 55vh;
        border: 1px solid darkGrey
    }
</style>
<?php View::endpush() ?>

<?php View::push('javascript') ?>
<script>
    'use strict';

    window.WT_OSM_ADMIN = (function () {
        const minZoom   = 2;
        const provider  = <?= json_encode($provider) ?>;
        const add_place = <?= json_encode($location->id() === null) ?>;

        let map = null;
        // map components

        // postcss_image_inliner breaks the autodetection of image paths.
        L.Icon.Default.imagePath = <?= json_encode(asset('css/images/')) ?>;

        // draggable marker
        let marker = L.marker(<?= json_encode($marker_position) ?>, {
            draggable: true,
        })
            .on('dragend', function () {
                let coords = marker.getLatLng();
                map.panTo(coords);
                $('#new_place_lati').val(Number(coords.lat).toFixed(5));
                $('#new_place_long').val(Number(coords.lng).toFixed(5));
            });

        //reset map to initial state
        let resetControl = L.Control.extend({
            options: {
                position: 'topleft'
            },
            onAdd: function (map) {
                let container = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');
                container.onclick = function () {
                    map.fitBounds(<?= json_encode($map_bounds) ?>, {padding: [50, 30]});
                    marker.setLatLng(<?= json_encode([$location->latitude(), $location->longitude()]) ?>);
                    $('form').trigger('reset');
                    return false;
                };
                let reset = <?= json_encode(I18N::translate('Reset to initial map state')) ?>;
                let anchor = L.DomUtil.create('a', 'leaflet-control-reset', container);
                anchor.setAttribute('aria-label', reset);
                anchor.href = '#';
                anchor.title = reset;
                anchor.role = 'button';
                let image = L.DomUtil.create('i', 'fas fa-redo', anchor);
                image.alt = reset;

                return container;
            }
        });

        // zoom control with localised text
        let zoomCtl = new L.control.zoom({
            zoomInTitle:  <?= json_encode(I18N::translate('Zoom in')) ?>,
            zoomOutTitle: <?= json_encode(I18N::translate('Zoom out')) ?>,
        });

        // Geocoder (place lookup)
        let geocoder = new L.Control.geocoder({
            defaultMarkGeocode: false,
            expand: 'click',
            showResultIcons: true,
            query: <?= json_encode($location->locationName()) ?>,
            placeholder: <?= json_encode(I18N::translate('Place')) ?>,
            errorMessage: <?= json_encode(I18N::translate('Nothing found.')) ?>,
            iconLabel: <?= json_encode(I18N::translate('Search')) ?>
        })
            .on('markgeocode', function (result) {
                let coords = result.geocode.center;
                let place = result.geocode.name.split(',', 1).toString();
                marker.setLatLng(coords);
                map.panTo(coords);
                if (add_place) {
                    $('#new_place_name').val(place);
                }
                $('#new_place_lati').val(Number(coords.lat).toFixed(5));
                $('#new_place_long').val(Number(coords.lng).toFixed(5));
            });

        /**
         *
         * @private
         */
        $(function () {
            // geocoder button tooltip
            $('.leaflet-control-geocoder-icon')
                .attr('title', <?= json_encode(I18N::translate('Search')) ?>);

            $('.editable').on('change', function () {
                let lat = $('#new_place_lati').val();
                let lng = $('#new_place_long').val();
                marker.setLatLng([lat, lng]);
                map.panTo([lat, lng]);
            });
        });

        // Create the map with all controls and layers
        map = L.map('osm-map', {
            minZoom: minZoom, // maxZoom set by leaflet-providers.js
            zoomControl: false,   // remove default
        })
            .addControl(new resetControl())
            .addControl(zoomCtl)
            .addControl(geocoder)
            .addLayer(marker)
            .addLayer(L.tileLayer(provider.url, provider.options))
            .fitBounds(<?= json_encode($map_bounds) ?>, {padding: [50, 30]})
            .on('zoomend', function () {
              if (!map.getBounds().contains(marker.getLatLng())) {
                map.panTo(marker.getLatLng());
              }
            });

        return 'Leaflet map interface for webtrees-2';
    })();
</script>
<?php View::endpush() ?>
