leaflet-exercise-cards.ts 36.1 KB
Newer Older
Tomas Pettersson's avatar
Tomas Pettersson committed
1 2 3 4
/// <reference path="def/uikit.d.ts" />
/// <reference path="def/leaflet.d.ts" />
/// <reference path="def/moment.d.ts" />
/// <reference path="def/leaflet-forcing-boundary.d.ts" />
5 6 7
/// <reference path="def/reqwest.d.ts" />import { GeoJSON } from "leaflet";


Tomas Pettersson's avatar
Tomas Pettersson committed
8 9 10 11


class EXLocation extends STWkit.LocationCard {

Tomas Pettersson's avatar
Tomas Pettersson committed
12
    private locationDiv: HTMLDivElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
13
    private locationForm: HTMLFormElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
14 15
    public obsDateInput: HTMLInputElement;
    public obsTimeInput: HTMLInputElement;
16 17 18
    private type: string;
    private subtype: string;                

Tomas Pettersson's avatar
Tomas Pettersson committed
19

20
    constructor(id, parentDiv, lang, langData, map, forcing, obs, type, subtype, initials) {
Tomas Pettersson's avatar
Tomas Pettersson committed
21
        var options: any = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
22 23 24 25 26 27 28 29 30 31
        options['single'] = true;
        options['line'] = true;
        options.polygon = {};
        options['polygon']['show'] = true;
        options['polygon']['name'] = 'Area';
        options['type'] = type;
        options['initials'] = initials;
        super(id, 'Specify time and location', parentDiv, lang, langData, map, forcing, options);

        var self = this;
32 33
        self.type = type;
        self.subtype = subtype;
Tomas Pettersson's avatar
Tomas Pettersson committed
34 35
        var fieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', 'uk-margin-top');
        this.locationForm.insertBefore(fieldset, this.locationForm.firstChild);
Tomas Pettersson's avatar
Tomas Pettersson committed
36 37

        var satCallbackFn = function (latlngs, geojsonfeature, timestamp, id) {
Tomas Pettersson's avatar
Tomas Pettersson committed
38
            self.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
39
            var geojson: any = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53
            geojson["type"] = "FeatureCollection";
            geojson["features"] = [];
            geojson["features"].push(geojsonfeature);
            var observation = {
                "id": id,
                "provider": "EMSA",
                "providerDataRef": null,
                "providerImgRef": null,
                "providerType": null,
                "type": "SAT",
                "date": moment.utc(timestamp).valueOf()
            };
            geojson.features[0].properties["observation"] = [];
            geojson.features[0].properties["observation"].push(observation);
Tomas Pettersson's avatar
Tomas Pettersson committed
54
            geojson.features[0].properties["simulation"] = {};
Tomas Pettersson's avatar
Tomas Pettersson committed
55
            self.populateCard(geojson);
56
            satdetectionHide();
Tomas Pettersson's avatar
Tomas Pettersson committed
57
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
58

Tomas Pettersson's avatar
Tomas Pettersson committed
59 60 61 62 63 64 65 66 67 68 69 70
        function legendBox(fieldset: HTMLFieldSetElement, color, text, size) {
            var rowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row uk-margin-remove', fieldset);
            var legendBox = <HTMLDivElement>L.DomUtil.create('div', 'legend-box', rowDiv);
            legendBox.style.backgroundColor = color;
            legendBox.style.width = size;
            legendBox.style.height = size;
            legendBox.title = text;
            var legendText = <HTMLDivElement>L.DomUtil.create('div', 'legend-text', rowDiv);
            legendText.textContent = text;
        }

        if (obs && obs.sat) {
Tomas Pettersson's avatar
Tomas Pettersson committed
71 72
            var obssatRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row', fieldset);
            self.satObs = new Observation.Sat(map, satCallbackFn, 'observation/oo');
Tomas Pettersson's avatar
Tomas Pettersson committed
73 74 75 76 77 78 79 80
            var satDetectionDiv = <HTMLDivElement>L.DomUtil.create('div', '', obssatRowDiv);
            var satDetectionList = <HTMLDListElement>L.DomUtil.create('dl', 'uk-description-list-line', satDetectionDiv);
            var satDetectionItem = <HTMLDListElement>L.DomUtil.create('dt', '', satDetectionList);
            var satDetectionHeading = <HTMLHeadingElement>L.DomUtil.create('h5', 'uk-width-1-1 chevron-title', satDetectionItem);
            satDetectionHeading.textContent = "Satellite oil detections";
            self.satDetectionChevronIcon = <HTMLSpanElement>L.DomUtil.create('span', 'uk-icon-chevron-down chevron-icon', satDetectionHeading);
            self.satDetectionContent = <HTMLDivElement>L.DomUtil.create('div', 'uk-animation-fade', satDetectionItem);
            self.satDetectionContent.style.display = 'none';
Tomas Pettersson's avatar
Tomas Pettersson committed
81
            var satdetectionShow = function () {
Tomas Pettersson's avatar
Tomas Pettersson committed
82 83 84 85
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-down')) {
                    self.satDetectionChevronIcon.classList.remove('uk-icon-chevron-down');
                    self.satDetectionChevronIcon.classList.add('uk-icon-chevron-up');
                    self.satDetectionContent.style.display = "";
Tomas Pettersson's avatar
Tomas Pettersson committed
86 87
                    self.satObs.show();
                }
88
            }
Tomas Pettersson's avatar
Tomas Pettersson committed
89
            var satdetectionHide = function () {
90
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-up')) {
Tomas Pettersson's avatar
Tomas Pettersson committed
91 92 93
                    self.satDetectionChevronIcon.classList.remove('uk-icon-chevron-up');
                    self.satDetectionChevronIcon.classList.add('uk-icon-chevron-down');
                    self.satDetectionContent.style.display = 'none';
Tomas Pettersson's avatar
Tomas Pettersson committed
94 95
                    self.satObs.hide();
                }
96 97 98 99
            }


            satDetectionHeading.onclick = function (evt) {
Tomas Pettersson's avatar
Tomas Pettersson committed
100
                if (self.satDetectionChevronIcon.classList.contains('uk-icon-chevron-down'))
101
                    satdetectionShow();
Tomas Pettersson's avatar
Tomas Pettersson committed
102
                else
103
                    satdetectionHide();
Tomas Pettersson's avatar
Tomas Pettersson committed
104
            };
Tomas Pettersson's avatar
Tomas Pettersson committed
105

Tomas Pettersson's avatar
Tomas Pettersson committed
106 107 108 109 110 111
            var satDetectionform = <HTMLFormElement>L.DomUtil.create('form', 'uk-form uk-form-stacked', self.satDetectionContent);
            satDetectionform.onsubmit = function (e) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            };
Tomas Pettersson's avatar
Tomas Pettersson committed
112

Tomas Pettersson's avatar
Tomas Pettersson committed
113 114
            var satDetectionfieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', '', satDetectionform);
            var satDetectionRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row uk-margin-top', satDetectionfieldset);
Tomas Pettersson's avatar
Tomas Pettersson committed
115
            super.addLabelDiv(satDetectionRowDiv, "Detection frequency", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-satdetection' target='_blank'>here</a>");
Tomas Pettersson's avatar
Tomas Pettersson committed
116 117 118 119 120 121 122 123 124 125 126
            legendBox(satDetectionfieldset, 'rgb(255, 0, 0)', 'Within 24 hours', '10px');
            legendBox(satDetectionfieldset, 'rgb(255, 153, 0)', 'Within 48 hours', '10px');
            legendBox(satDetectionfieldset, 'rgb(255, 255, 0)', 'More than two days ago', '10px');
            legendBox(satDetectionfieldset, 'rgb(255, 255, 255)', 'Older', '10px');

        }

        self.datetimeFormat = 'YYYY-MM-DD HH:mm';
        self.datetimeTFormat = 'YYYY-MM-DDTHH:mm:ss.000';
        self.dateFormat = 'YYYY-MM-DD';
        self.timeFormat = 'HH:mm';
Tomas Pettersson's avatar
Tomas Pettersson committed
127 128
        var obsdateRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row uk-margin-remove', fieldset);
        super.addLabelDiv(obsdateRowDiv, "Observation time (UTC)", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-time' target='_blank'>here</a>");
Tomas Pettersson's avatar
Tomas Pettersson committed
129
        var obsdateDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-controls uk-form-icon uk-width-1-1', obsdateRowDiv);
Tomas Pettersson's avatar
Tomas Pettersson committed
130
        obsdateDiv.id = 'guide' + initials + 'date';
Tomas Pettersson's avatar
Tomas Pettersson committed
131 132 133 134 135 136 137
        var obsdateIcon = <HTMLSpanElement>L.DomUtil.create('span', 'uk-icon-calendar', obsdateDiv);
        self.obsDateInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', obsdateDiv);
        self.obsDateInput.type = 'text';
        self.obsDateInput.placeholder = self.dateFormat;
        self.obsTimeInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', obsdateDiv);
        self.obsTimeInput.type = 'text';

Tomas Pettersson's avatar
Tomas Pettersson committed
138 139
        self.obsDateInput.onchange = function () { self.fireChangeFn(self); };
        self.obsTimeInput.onchange = function () { self.fireChangeFn(self); };
Tomas Pettersson's avatar
Tomas Pettersson committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167


        UIkit.ready(function () {
            var startDatePicker = UIkit.datepicker(<any>self.obsDateInput, { format: self.dateFormat });
            var startTimePicker = UIkit.timepicker(<any>self.obsTimeInput, {});

            self.defaults();
        });

    }

    public defaults() {
        super.defaults();
        var self = this;
        if (document.body.contains(self.obsDateInput)) {
            if (self.obsDateInput.value == '') {
                var initDate = moment.utc();
                self.obsDateInput.value = initDate.format(self.dateFormat);
                self.obsTimeInput.value = initDate.startOf('hour').format(self.timeFormat);
            }
        }
    }

    public populateCard(geojson) {
        var self = this;
        super.populateCard(geojson);
        var simulation = geojson.features[0].properties.simulation;
        var observation = geojson.features[0].properties.observation[0];
Tomas Pettersson's avatar
Tomas Pettersson committed
168
        var datetime = simulation.startDate;
Tomas Pettersson's avatar
Tomas Pettersson committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        if (geojson.features[0].properties.observation.length > 0) {
            var observation = geojson.features[0].properties.observation[0];
            datetime = observation.date;
        }
        var date = moment.utc(datetime).format(self.dateFormat);
        self.obsDateInput.value = date;
        var time = moment.utc(datetime).format(self.timeFormat);
        self.obsTimeInput.value = time;
        self.fireChangeFn(this);
    }

    public populateData(geojson) {
        super.populateData(geojson);
        var self = this;
        var observation = {
            "id": null,
            "provider": "USER",
            "providerDataRef": null,
            "providerImgRef": null,
            "providerType": null,
            "type": "MANUAL",
            "date": moment.utc(self.obsDateInput.value + ' ' + self.obsTimeInput.value, self.datetimeFormat).valueOf()

        };
193 194 195
        var layer:any = L.GeoJSON.geometryToLayer(geojson.features[0]);
        var center = null;
        if (layer._latlng) center = layer._latlng; else center = layer.getBounds().getCenter()
Tomas Pettersson's avatar
Tomas Pettersson committed
196
        geojson.features[0].properties["primary"] = 'PADM';        
197 198 199 200
        geojson.features[0].properties["type"] = self.type;        
        geojson.features[0].properties["subtype"] = self.subtype;        
        geojson.features[0].properties["meanLat"] = center.lat;        
        geojson.features[0].properties["meanLng"] = center.lng;        
Tomas Pettersson's avatar
Tomas Pettersson committed
201 202
        geojson.features[0].properties["observation"] = [];
        geojson.features[0].properties["observation"].push(observation);
Tomas Pettersson's avatar
Tomas Pettersson committed
203
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
204
}
Tomas Pettersson's avatar
Tomas Pettersson committed
205

Tomas Pettersson's avatar
Tomas Pettersson committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

class EXAmount extends STWkit.AccordionCard {
    public oncallback: Function;
    public amountInput: HTMLInputElement;
    public amountSelect: HTMLSelectElement;
    public nextButton: any;

    constructor(id, parentDiv, lang, map, type, initials) {
        var amountDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1 uk-margin-top', parentDiv);
        super(id, 'Amount', parentDiv, amountDiv);
        var self = this;
        var form = <HTMLFormElement>L.DomUtil.create('form', 'uk-form uk-form-stacked', amountDiv);
        form.setAttribute('novalidate', '');
        form.onsubmit = function (e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
224 225
        form.onkeypress = function (e) {
            var key = e.charCode || e.keyCode || 0;
Tomas Pettersson's avatar
Tomas Pettersson committed
226
            if (key == 13) e.preventDefault();
Tomas Pettersson's avatar
Tomas Pettersson committed
227
        };
Tomas Pettersson's avatar
Tomas Pettersson committed
228 229 230 231 232 233 234 235 236 237

        function addOption(parent, value, txt) {
            var option = <HTMLOptionElement>L.DomUtil.create('option', '', parent);
            option.value = value;
            option.textContent = txt;
        }


        var fieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', '', form);
        var amountRowDiv: any = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row', fieldset);
Tomas Pettersson's avatar
Tomas Pettersson committed
238
        amountRowDiv.id = 'guide' + initials + 'amountvalue';
Tomas Pettersson's avatar
Tomas Pettersson committed
239 240 241 242 243
        amountRowDiv.guideFn = function () {
            self.amountInput.value = '10';
            validate();
        }

Tomas Pettersson's avatar
Tomas Pettersson committed
244
        super.addLabelDiv(amountRowDiv, "Amount", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-amount' target='_blank'>here</a>");
Tomas Pettersson's avatar
Tomas Pettersson committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        var amountValueDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1', amountRowDiv);
        self.amountInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-4', amountValueDiv);
        self.amountInput.type = 'number';
        self.amountInput.step = '10';
        self.amountInput.min = '0';
        var amountUnitDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-2 uk-form-select select', amountValueDiv);
        amountUnitDiv.setAttribute('data-uk-form-select', '');
        var selectedAmountUnit = <HTMLSpanElement>L.DomUtil.create('span', '', amountUnitDiv);
        self.amountSelect = <HTMLSelectElement>L.DomUtil.create('select', '', amountUnitDiv);
        addOption(self.amountSelect, 'm3', '');
        addOption(self.amountSelect, 'tonnes', 'tonnes');


        self.amountInput.onchange = function () {
            validate();
        };

        function validate() {
            var amountValue = parseInt(self.amountInput.value);
            var amountOk = false;
            if (amountValue > 0) amountOk = true;
            if (amountOk) {
                self.status = true;
                STWkit.AccordionCard.enableNext(self.nextButton, true);
                (self.oncallback && self.oncallback());
            } else {
                self.clear();
            }
        };


        var clearDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-clearfix', amountDiv);
        var clearButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-left', clearDiv);
        clearButton.textContent = 'Clear';
        clearButton.onclick = function () {
            self.clear();
        };
        self.nextButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-right', clearDiv);
Tomas Pettersson's avatar
Tomas Pettersson committed
283
        self.nextButton.id = 'guide' + initials + 'amount';
Tomas Pettersson's avatar
Tomas Pettersson committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        self.nextButton.textContent = 'Next';
        self.nextButton.guideFn = function () {
            self.nextButton.click();
        }
        STWkit.AccordionCard.enableNext(self.nextButton, false);
        self.nextButton.onclick = function () {
            if (!STWkit.AccordionCard.isEnabled(self.nextButton)) {
                STWkit.AccordionCard.warningMsg('Mandatory fields missing',
                    'Specify a valid <b>amount</b>.');
                return;
            }

            (self.oncallback && self.oncallback(true));
        };

        UIkit.ready(function () {
            self.defaults();
        });
    }

    public defaults() {
        var self = this;
    }
    public populateCard(geojson) {
        var self = this;
        var simulation = geojson.features[0].properties.simulation;
Tomas Pettersson's avatar
Tomas Pettersson committed
310

Tomas Pettersson's avatar
Tomas Pettersson committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        self.amountInput.value = simulation.amount;
        var amountevt = document.createEvent('Event');
        amountevt.initEvent("change", true, true);
        self.amountInput.dispatchEvent(amountevt);
        self.amountSelect.value = simulation.amountUnit;
    }

    public populateData(geojson) {
        var self = this;
        geojson.features[0].properties["simulation"]["amount"] = self.amountInput.value;
        geojson.features[0].properties["simulation"]["amountUnit"] = self.amountSelect.options[self.amountSelect.selectedIndex].value;
    }


    public clear() {
        var self = this;
        super.clear();
        self.amountInput.value = '';
        STWkit.AccordionCard.enableNext(self.nextButton, false);
        self.status = false;
        (self.oncallback && self.oncallback());
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
333 334 335
}


Tomas Pettersson's avatar
Tomas Pettersson committed
336 337 338 339
class TrajectoryLineHandler extends LineHandler {

    private _errorShown : any;
    private _mouseDownOrigin : any;
Tomas Pettersson's avatar
Tomas Pettersson committed
340 341 342 343 344 345 346
    private _map : any;
    private _currentLatLng: any;
    private _enabled: any;
    private _mouseMarker: any;
    private _clickHandled: any;
    private _disableMarkers: any;

Tomas Pettersson's avatar
Tomas Pettersson committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    constructor(time, map, options){
        super(map,options);
    }

    private autoPoint(e, latlng) {
        if (this._errorShown)
            return;

        if (this._mouseDownOrigin) {
            var originalEvent = e.originalEvent;
            //if(originalEvent.button == 2) {
            var distance = L.point(originalEvent.clientX, originalEvent.clientY)
                .distanceTo(this._mouseDownOrigin);

            //if (Math.abs(distance) < 9 * (window.devicePixelRatio || 1)) {
            if (Math.abs(distance) > 6 * (window.devicePixelRatio || 1)) {
Pettersson Tomas's avatar
Pettersson Tomas committed
363 364 365
                // if (this.time.length > 0) {
                    (<any>L).drawLocal.draw.handlers.polyline.tooltip.cont = 'Relase button to stop drawing';                                        
                    // (<any>L).drawLocal.draw.handlers.polyline.tooltip.cont = moment.utc(this.time.pop()).format('YYYY-MM-DD HH:mm')+' ('+this.time.length+' left)';                                        
Tomas Pettersson's avatar
Tomas Pettersson committed
366 367
                    super.addVertex(latlng);
                    this._mouseDownOrigin = L.point(originalEvent.clientX, originalEvent.clientY);
Pettersson Tomas's avatar
Pettersson Tomas committed
368 369 370 371 372 373 374
                // } else {
                //     super._finishShape();
                //     this._mouseDownOrigin = null;
                //     this._clickHandled = false;
                //     this._disableMarkers = false;                    
                //     return;
                // }
Tomas Pettersson's avatar
Tomas Pettersson committed
375 376 377 378
            }
            //}
        }
    };
Tomas Pettersson's avatar
Tomas Pettersson committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    private _onMouseMove(e) {
        var newPos = this._map.mouseEventToLayerPoint(e.originalEvent);
        var latlng = this._map.layerPointToLatLng(newPos);

        // Save latlng
        // should this be moved to _updateGuide() ?
        this._currentLatLng = latlng;

        super._updateTooltip(latlng);

        if (e.originalEvent.ctrlKey) {
            super.deleteLastVertex(e);
        }
        else {
            this.autoPoint(e, latlng);
        }
        if (this._enabled) {
            // Update the guide line
            super._updateGuide(newPos);
Tomas Pettersson's avatar
Tomas Pettersson committed
398
    
Tomas Pettersson's avatar
Tomas Pettersson committed
399 400 401
            // Update the mouse marker position
            this._mouseMarker.setLatLng(latlng);
        }
Tomas Pettersson's avatar
Tomas Pettersson committed
402

Tomas Pettersson's avatar
Tomas Pettersson committed
403 404 405
        L.DomEvent.preventDefault(e.originalEvent);
        L.DomEvent.stopPropagation(e.originalEvent);
    };
Tomas Pettersson's avatar
Tomas Pettersson committed
406

Tomas Pettersson's avatar
Tomas Pettersson committed
407
}
Tomas Pettersson's avatar
Tomas Pettersson committed
408

Tomas Pettersson's avatar
Tomas Pettersson committed
409 410 411
class EXTrajectory extends STWkit.AccordionCard {
    public oncallback: Function;
    public lineButton: HTMLButtonElement;
Tomas Pettersson's avatar
Tomas Pettersson committed
412
    private lineHandler : any;    
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
413
    private drawnfeature : any;    
Tomas Pettersson's avatar
Tomas Pettersson committed
414
    private trajectoryLayer : L.GeoJSON;
Tomas Pettersson's avatar
Tomas Pettersson committed
415
    private trajectoryLabelLayer : any;
Pettersson Tomas's avatar
Pettersson Tomas committed
416
    private trajMarkerArray : any[];
Tomas Pettersson's avatar
Tomas Pettersson committed
417 418
    public exitControl: L.Control;
    public positions: any[];    
Tomas Pettersson's avatar
Tomas Pettersson committed
419 420
    private map: any;    
    private time: any;    
Pettersson Tomas's avatar
Pettersson Tomas committed
421 422
    private from: any;    
    private to: any;    
Tomas Pettersson's avatar
Tomas Pettersson committed
423
    public nextButton: any;
Pettersson Tomas's avatar
Pettersson Tomas committed
424 425 426 427
    endDateInput: HTMLInputElement;
    endTimeInput: HTMLInputElement;
    dateFormat: string;
    timeFormat: string;       
Tomas Pettersson's avatar
Tomas Pettersson committed
428

Pettersson Tomas's avatar
Pettersson Tomas committed
429
    constructor(id, parentDiv, lang, langData, map, domain, type, subtype, initials) {
Tomas Pettersson's avatar
Tomas Pettersson committed
430 431 432
        var trajectoryDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1 uk-margin-top', parentDiv);
        super(id, 'Trajectory', parentDiv, trajectoryDiv);
        var self = this;
Tomas Pettersson's avatar
Tomas Pettersson committed
433
        this.map = map;
Tomas Pettersson's avatar
Tomas Pettersson committed
434 435 436 437 438 439 440 441 442 443 444
        var form = <HTMLFormElement>L.DomUtil.create('form', 'uk-form uk-form-stacked', trajectoryDiv);
        form.setAttribute('novalidate', '');
        form.onsubmit = function (e) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        };
        form.onkeypress = function (e) {
            var key = e.charCode || e.keyCode || 0;
            if (key == 13) e.preventDefault();
        };
Pettersson Tomas's avatar
Pettersson Tomas committed
445 446 447
        self.dateFormat = 'YYYY-MM-DD';
        self.timeFormat = 'HH:mm';

Tomas Pettersson's avatar
Tomas Pettersson committed
448 449 450 451 452 453
        self.positions = [];
        var positionLabelGrid = <HTMLDivElement>L.DomUtil.create('div', 'uk-grid uk-margin-top', form);
        var positionlabelDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-1', positionLabelGrid);
        super.addLabelDiv(positionlabelDiv, "Position", "See more information <a style='color:#faa732;' href='help/classic/#" + type + "-" + initials + "-position' target='_blank'>here</a>");
        var positionDiv: any = <HTMLDivElement>L.DomUtil.create('div', '', form);
        positionDiv.id = 'guide' + initials + 'pos';
Pettersson Tomas's avatar
Pettersson Tomas committed
454 455 456 457 458 459 460 461 462 463 464
        var fieldset = <HTMLFieldSetElement>L.DomUtil.create('fieldset', 'uk-margin-top', form);        
        var endRowDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-row', fieldset);
        super.addLabelDiv(endRowDiv, "End point date (UTC)", "See more information <a style='color:#faa732;' href='help/classic/?domain=" + domain.toLowerCase() + "#" + type + "-" + subtype + "-start' target='_blank'>here</a>");
        var endDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-form-controls uk-form-icon uk-width-1-1', endRowDiv);
        var endIcon = <HTMLSpanElement>L.DomUtil.create('span', 'uk-icon-calendar', endDiv);
        self.endDateInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', endDiv);
        self.endDateInput.type = 'text';
        self.endDateInput.placeholder = self.dateFormat;
        self.endTimeInput = <HTMLInputElement>L.DomUtil.create('input', 'uk-width-1-2', endDiv);
        self.endTimeInput.type = 'text';

Tomas Pettersson's avatar
Tomas Pettersson committed
465 466 467 468 469
        var positionButtonGrid = <HTMLDivElement>L.DomUtil.create('div', 'uk-grid uk-grid-small', positionDiv);
        var drawDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-width-1-2', positionButtonGrid);
        var drawButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-button-small uk-align-left uk-margin-remove', drawDiv);
        drawButton.textContent = 'Free hand draw';

470 471 472
        function enddateonchange() {
            
            var newdate:any = moment.utc(self.endDateInput.value + ' ' + self.endTimeInput.value, self.datetimeFormat);
473 474 475
            if (newdate.isBefore(self.from)) {
                self.endDateInput.value =  self.to.format(self.dateFormat);
                self.endTimeInput.value =  self.to.startOf('hour').format(self.timeFormat);
476 477 478
                STWkit.AccordionCard.warningMsg('End point date outside simulation period', 'End point date cannot be before simulation period start date');
            } else {
                var diff = Math.abs(self.from - newdate);
479
                var nrofhours = ((diff/1000)/60)/60;
480 481
    
                if (nrofhours <= 72) {
482 483
                    self.durationhours = nrofhours;      
                    self.to = moment.utc(self.endDateInput.value + ' ' + self.endTimeInput.value, self.datetimeFormat);      
484 485 486 487 488 489 490 491
                    self.refreshTrajectory();
                    self.fireChangeFn(self);     
                    delete self.durationhours;            
                } else {
                    self.endDateInput.value =  self.to.format(self.dateFormat);
                    self.endTimeInput.value =  self.to.startOf('hour').format(self.timeFormat);
                    STWkit.AccordionCard.warningMsg('Simulation period too long', 'The number of simulation hours cannot exceend 72 hours (Simulation period start date - End point date)');
                }
492
            }
493
        }
494

495 496
        self.endDateInput.onchange = function (evt) {
            enddateonchange();
Pettersson Tomas's avatar
Pettersson Tomas committed
497 498 499
        };
        
        self.endTimeInput.onchange = function (evt) {
500
            enddateonchange();
Pettersson Tomas's avatar
Pettersson Tomas committed
501 502
        };

Tomas Pettersson's avatar
Tomas Pettersson committed
503 504 505 506 507 508 509 510 511 512 513 514
        positionDiv.guideFn = function () {
            var geojson = {};
            geojson["type"] = "FeatureCollection";
            geojson["features"] = [];
            var feature = {};
            feature['type'] = "Feature";
            feature['geometry'] = {};
            feature['geometry']['type'] = "Point";
            feature['geometry']['coordinates'] = [];
            // feature['geometry']['coordinates'].push(19.0);
            // feature['geometry']['coordinates'].push(56.0);
            geojson["features"].push(feature);
Tomas Pettersson's avatar
Tomas Pettersson committed
515
            // self.control.addGeoJSON(geojson);
Tomas Pettersson's avatar
Tomas Pettersson committed
516
        }
Tomas Pettersson's avatar
Tomas Pettersson committed
517

Tomas Pettersson's avatar
Tomas Pettersson committed
518
        var color = '#CA5A1B';
Tomas Pettersson's avatar
Tomas Pettersson committed
519
        this.lineHandler = new TrajectoryLineHandler(null, map, {
Tomas Pettersson's avatar
Tomas Pettersson committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
            allowIntersection: true,   
            icon: new L.DivIcon({
                        iconSize: new L.Point(8, 8),
                        className: 'leaflet-div-icon leaflet-editing-icon'
                    }),                                      
            drawError: {
                color: color,
                timeout: 1000
            },
            shapeOptions: {
                color: color
            },
            showArea: true,
            metric: true,
            repeatMode : false
Tomas Pettersson's avatar
Tomas Pettersson committed
535
        });
Tomas Pettersson's avatar
Tomas Pettersson committed
536 537
        this.lineHandler.type = 'draw'+id;      
        
Tomas Pettersson's avatar
Tomas Pettersson committed
538 539 540 541


        map.on('zoomend', function () {
            if (self.map.hasLayer(self.trajectoryLabelLayer)) {
Pettersson Tomas's avatar
Pettersson Tomas committed
542
                self.updateTrajectoryLabelVisibility();
Tomas Pettersson's avatar
Tomas Pettersson committed
543 544 545
            }
        });        
        
Tomas Pettersson's avatar
Tomas Pettersson committed
546 547 548 549
        map.on('draw:created', function (e) {
            var type = e.layerType,
                layer = e.layer;
            if (type == 'draw'+id) {
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
550 551
                self.drawnfeature = layer.toGeoJSON();
                self.refreshTrajectory();                    
Tomas Pettersson's avatar
Tomas Pettersson committed
552 553 554 555 556 557 558 559
                var toggleevt = document.createEvent("CustomEvent");
                toggleevt.initCustomEvent('container:toggleVisibility', false, false, {
                    'show': true
                });
                window.dispatchEvent(toggleevt);
                self.fireChangeFn(self);
                if (self.exitControl) map.removeControl(self.exitControl);
                self.exitControl = null;
Tomas Pettersson's avatar
Tomas Pettersson committed
560 561 562 563 564
                if (self.getLatLngArray().length > 0) {
                    self.status = true;
                    STWkit.AccordionCard.enableNext(self.nextButton, true);
                    (self.oncallback && self.oncallback());
                }
Tomas Pettersson's avatar
Tomas Pettersson committed
565 566

            }
Tomas Pettersson's avatar
Tomas Pettersson committed
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
        });             
        this.trajectoryLayer = new L.GeoJSON(null, {});
        this.trajMarkerArray = [];
        this.trajectoryLabelLayer = L.geoJson(null, {
            'pointToLayer': function (feature: any, latlng: L.LatLng) {
                var iconOpts: any = {
                    iconSize: [25, 41],
                    iconAnchor: [40, 61],
                    className: 'iconHiddentextIcon',
                    clickable: false,
                    html: '<span class="trajLabel">' + moment.utc(feature.properties.time).format('YYYY-MM-DD HH:mm') + ' [' + STWkit.convertDDtoDDM(latlng.lat, true) + ', ' + STWkit.convertDDtoDDM(latlng.lng, false) + '] </span>'
                };
                var marker: any = L.marker(latlng, {
                    clickable: false,
                    icon: L.divIcon(iconOpts)
                }
                );
                marker.visible = true;
                self.trajMarkerArray.push(marker);
Tomas Pettersson's avatar
Tomas Pettersson committed
586
                return marker;
Tomas Pettersson's avatar
Tomas Pettersson committed
587 588
            }
        });
Tomas Pettersson's avatar
Tomas Pettersson committed
589
        
Tomas Pettersson's avatar
Tomas Pettersson committed
590 591
        map.addLayer(this.trajectoryLayer);  
        map.addLayer(this.trajectoryLabelLayer);  
Tomas Pettersson's avatar
Tomas Pettersson committed
592 593

        drawButton.onclick = function () {
Tomas Pettersson's avatar
Tomas Pettersson committed
594
            self.clear();
Tomas Pettersson's avatar
Tomas Pettersson committed
595 596 597 598 599
            var toggleevt = document.createEvent("CustomEvent");
            toggleevt.initCustomEvent('container:toggleVisibility', false, false, {
                'show': false
            });
            window.dispatchEvent(toggleevt);
Tomas Pettersson's avatar
Tomas Pettersson committed
600 601

            self.lineHandler.enable();
Tomas Pettersson's avatar
Tomas Pettersson committed
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
            self.exitControl = new L.Control({ position: 'bottomright' });
            self.exitControl.onAdd = function (map: L.Map) {
                var container = L.DomUtil.create('div', 'exit-control');
                var exitPanel = L.DomUtil.create('div', 'uk-panel uk-panel-box', container);
                var finishButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-button-small uk-button-primary uk-margin-right', exitPanel);
                finishButton.textContent = 'Finish';
                finishButton.onclick = function (e) {
                    map.fire('draw:canceled');
                };
                finishButton.style.display = 'none';
                var cancelButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-button-small', exitPanel);
                cancelButton.textContent = 'Cancel';
                cancelButton.onclick = function (e) {
                    if (self.exitControl) map.removeControl(self.exitControl);
                    self.exitControl = null;
                    var toggleevt = document.createEvent("CustomEvent");
                    toggleevt.initCustomEvent('container:toggleVisibility', false, false, {
                        'show': true
                    });
                    window.dispatchEvent(toggleevt);
                    self.clear();
                };

                L.DomEvent.disableClickPropagation(container);
                return container;
            };
            self.exitControl.addTo(map);

        };


        var clearDiv = <HTMLDivElement>L.DomUtil.create('div', 'uk-clearfix', trajectoryDiv);
        var clearButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-left', clearDiv);
        clearButton.textContent = 'Clear';
        clearButton.onclick = function () {
            self.clear();
        };
        self.nextButton = <HTMLButtonElement>L.DomUtil.create('button', 'uk-button uk-margin-top uk-align-right', clearDiv);
        self.nextButton.id = 'guide' + initials + 'trajectory';
        self.nextButton.textContent = 'Next';
        self.nextButton.guideFn = function () {
            self.nextButton.click();
        }
        STWkit.AccordionCard.enableNext(self.nextButton, false);
        self.nextButton.onclick = function () {
            if (!STWkit.AccordionCard.isEnabled(self.nextButton)) {
                STWkit.AccordionCard.warningMsg('Mandatory fields missing',
                    'Specify a valid <b>position</b>.');
                return;
            }

            (self.oncallback && self.oncallback(true));
        };

        UIkit.ready(function () {
Pettersson Tomas's avatar
Pettersson Tomas committed
657 658 659
            var endDatePicker = UIkit.datepicker(<any>self.endDateInput, {format: self.dateFormat });
            var endTimePicker = UIkit.timepicker(<any>self.endTimeInput, {});

Tomas Pettersson's avatar
Tomas Pettersson committed
660 661 662 663
            self.defaults();
        });
    }

Tomas Pettersson's avatar
Tomas Pettersson committed
664 665 666
    public changeFn(changeCard) {
        var self = this;
        if ((typeof changeCard.from !== 'undefined') && (typeof changeCard.to !== 'undefined')) {
Pettersson Tomas's avatar
Pettersson Tomas committed
667 668
            self.from = changeCard.from.clone();
            self.to = changeCard.to.clone();
Pettersson Tomas's avatar
Pettersson Tomas committed
669 670 671 672
            if (self.endDateInput) {
                self.endDateInput.value =  self.to.format(self.dateFormat);
                self.endTimeInput.value =  self.to.startOf('hour').format(self.timeFormat);
            }
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
673
            self.refreshTrajectory();
Pettersson Tomas's avatar
Pettersson Tomas committed
674
       }
Tomas Pettersson's avatar
Tomas Pettersson committed
675
    }
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
676 677 678
    
    private refreshTrajectory(){
        var self = this;
Tomas Pettersson's avatar
Tomas Pettersson committed
679

Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
680 681 682 683 684 685 686 687 688 689 690 691
        if (this.drawnfeature && this.drawnfeature.geometry && this.drawnfeature.geometry.coordinates.length > 2) {
            
            self.trajMarkerArray = [];
            self.trajectoryLayer.clearLayers();
            self.trajectoryLabelLayer.clearLayers();
    
            var timeIncrement = 15;
            var currentlength = self.drawnfeature.geometry.coordinates.length;
            var wantedTimeIncrementlength = Math.round(((Math.abs(this.from - this.to)/1000)/60) / timeIncrement);
    
            var coords = self.drawnfeature.geometry.coordinates.slice(0);
    
692
            var index  = 1;
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
693
            while(coords.length < wantedTimeIncrementlength) {
694 695
                // too small, add points
                if (index >= coords.length-1) index = 1;
Pettersson Tomas's avatar
testing  
Pettersson Tomas committed
696 697
                var newpoint = [(coords[index][0]+coords[index+1][0])/2,(coords[index][1]+coords[index+1][1])/2];
                coords.splice(index+1, 0, newpoint);
698
                index += 2;
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
699
            }
Pettersson Tomas's avatar
testing  
Pettersson Tomas committed
700 701 702 703


            while(coords.length > wantedTimeIncrementlength) {
                // too big, remove random points
704
                var index:number  = self.getRandomInt(1, currentlength-1);
Pettersson Tomas's avatar
testing  
Pettersson Tomas committed
705 706 707
                coords.splice(index, 1);
            }            

Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
708 709 710 711
            self.time = [];
            var t = self.from.clone();
            for (var i = 0; i < coords.length; i++) {
                t = t.add(timeIncrement,'m');
712
                self.time.push(t.valueOf());
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
            }
            self.time[self.time.length-1] = self.to.valueOf();
    
            var trajfeature: any = STWkit.createFeature("LineString");
            trajfeature.geometry.coordinates = coords;
    
    
            self.trajectoryLayer.addData(trajfeature);
            var trajpointfeaturecollection = STWkit.featurecollection();
    
            for (var i = 0; i < coords.length; i++) {
                var trajpointfeature: any = STWkit.createFeature("Point");
                trajpointfeature.geometry.coordinates = coords[i];
                trajpointfeature.properties.time = self.time[i];
                if (i == 0) trajpointfeature.properties.start = true;
                if (i == self.time.length - 1) trajpointfeature.properties.end = true;
                trajpointfeaturecollection.features.push(trajpointfeature);
            }
    
            self.trajectoryLabelLayer.addData(trajpointfeaturecollection);    
                        
            self.updateTrajectoryLabelVisibility();
Pettersson Tomas's avatar
Pettersson Tomas committed
735
        }
Pettersson Tomas's avatar
recode  
Pettersson Tomas committed
736 737 738 739 740

    }

    private getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
Pettersson Tomas's avatar
Pettersson Tomas committed
741
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
742

Pettersson Tomas's avatar
Pettersson Tomas committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756
    public setTime() {
        var self = this;
        self.time = [];
        if (self.timeIncrement > 0 && self.from.isBefore(self.to)) {
            var t = self.from.clone();
            for (var i = 0; i < self.trajlength; i++) {
                self.time.push(t.valueOf());
                t = t.add(self.timeIncrement,'m');
            }
            self.time[self.time.length-1] = self.to.valueOf();
            return true;
        }
        return false;
    }
Tomas Pettersson's avatar
Tomas Pettersson committed
757

Pettersson Tomas's avatar
Pettersson Tomas committed
758 759 760 761 762 763 764 765 766 767 768 769
    private updateTrajectoryLabelTimeValues() {
        var self = this;        
        self.trajMarkerArray = [];        
        self.trajectoryLabelLayer.clearLayers();    
        for (var i = 0; i < self.time.length; i++) 
            self.trajpointfeaturecollection.features[i].properties.time = self.time[i];
        
        self.trajectoryLabelLayer.addData(self.trajpointfeaturecollection);    
        self.updateTrajectoryLabelVisibility();
    }

    private updateTrajectoryLabelVisibility() {
Tomas Pettersson's avatar
Tomas Pettersson committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
        var self = this;
        if (self.trajMarkerArray.length > 2) {
            var occupied = new Array();
            occupied[0] = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[0]._latlng));
            occupied[1] = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[self.trajMarkerArray.length - 1]._latlng));
            var k = 2;
            for (var i = 1; i < self.trajMarkerArray.length - 1; i++) {
                var rect = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[i]._latlng));
                var ok = true;
                for (var j = 0; j < occupied.length; j++) {
                    if (STWkit.intersect(rect, occupied[j])) {
                        ok = false;
                        break;
                    }
                }
                if (ok) {
                    occupied[k] = STWkit.getRectangle(self.map.latLngToLayerPoint(self.trajMarkerArray[i]._latlng));
                    k++;
                    if (!self.trajMarkerArray[i].visible) {
                        self.trajectoryLabelLayer.addLayer(self.trajMarkerArray[i]);
                        self.trajMarkerArray[i].visible = true;
                    }
                } else {
                    if (self.trajMarkerArray[i].visible) {
                        self.trajectoryLabelLayer.removeLayer(self.trajMarkerArray[i]);
                        self.trajMarkerArray[i].visible = false;
                    }
                }
            }
        }
    };

Tomas Pettersson's avatar
Tomas Pettersson committed
802 803 804 805 806 807 808 809 810
    private getLatLngArray() {
        var self = this;
        var latlngs = [];
        self.trajectoryLayer.getLayers().forEach (function (layer:any) {
            if (layer._latlngs) latlngs.push(layer._latlngs); else latlngs.push([layer._latlng]);
         });
        return latlngs;    
    }

Tomas Pettersson's avatar
Tomas Pettersson committed
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    public validate() {
        if (this.positions.length == 0) return;
        this.status = true;
        STWkit.AccordionCard.enableNext(this.nextButton, true);
        (this.oncallback && this.oncallback());
    };


    public defaults() {
        var self = this;
    }
    public populateCard(geojson) {
        var self = this;
    }

    public populateData(geojson) {
        var self = this;
Tomas Pettersson's avatar
Tomas Pettersson committed
828 829 830 831 832 833 834 835 836 837 838 839
        var feature = STWkit.createFeature('LineString');
        var props = feature.properties;
        props['auxiliary'] = 'exercise';
        props['time'] = self.time;
        var coords = feature.geometry.coordinates;
        var latlngs:Array<L.LatLng> = self.getLatLngArray()[0];
        for (let i = 0; i < latlngs.length; i++) {
            const latlng = latlngs[i];
            coords.push([latlng.lng, latlng.lat]);
        }
        geojson.features.push(feature);

Tomas Pettersson's avatar
Tomas Pettersson committed
840 841 842 843 844 845
    }


    public clear() {
        var self = this;
        super.clear();
846
        self.drawnfeature = null;
Tomas Pettersson's avatar
Tomas Pettersson committed
847 848 849
        self.trajectoryLabelLayer.clearLayers();
        self.trajectoryLayer.clearLayers()
        self.trajMarkerArray = [];
Tomas Pettersson's avatar
Tomas Pettersson committed
850
        if (self.lineHandler._enabled) self.lineHandler.disable();
Tomas Pettersson's avatar
Tomas Pettersson committed
851 852 853 854 855 856
        if (self.nextButton) STWkit.AccordionCard.enableNext(self.nextButton, false);
        (self.oncallback && self.oncallback());
    }
}