/* global L */

import "../leaflet/leaflet.min.js";

import getCoordinates from "../models/nominatim.js";
import orderModel from "../models/order-model.js";


export default class MapView extends HTMLElement {
    constructor() {
        super();

        this.map = null;
    }

    async connectedCallback() {
        const orderNumber = window.location.hash.replace("#map/", "");

        this.orderInfo = await orderModel.getOrder(orderNumber);
        this.innerHTML = `<div class="container-small">
        <camera-component></camera-component>
        <h2 class="seccondHeader"> MapView</h2>
        <div id="map" class="map"></div>
            <p class="seccondHeader">
                Click marker for additional information!
            <p>
        </div>
        </div>
        
        `;

        this.renderMap();
    }

    renderMap() {
        this.map = L.map('map').setView([56.18219, 15.59094], 11);

        L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        }).addTo(this.map);

        this.renderMarkers();

        this.renderLocation();
    }

    async renderMarkers() {
        const orderNumber = window.location.hash.replace("#map/", "");

        this.orderInfo = await orderModel.getOrder(orderNumber);

        //let coordinates = [56.2345, 15.6034];

        //L.marker(coordinates).addTo(this.map);

        //let adress = "Bergsgatan 1, Karlskrona";

        let adress = this.orderInfo.address + ", " + this.orderInfo.city;

        const results = await getCoordinates(adress);

        L.marker([
            parseFloat(results[0].lat),
            parseFloat(results[0].lon),
        ]).addTo(this.map);
        L.marker([
            parseFloat(results[0].lat),
            parseFloat(results[0].lon),
        ]).bindPopup(`
        <strong>Order Information:</strong><br>
        <p><strong>Namn:</strong> ${this.orderInfo.name}</p>
        <p><strong>Address:</strong> ${this.orderInfo.address}</p>
        <p><strong>Stad:</strong> ${this.orderInfo.city}</p>
        <p><strong>Zip:</strong> ${this.orderInfo.zip}</p>
        <p><strong>Country:</strong> ${this.orderInfo.country}</p>
    `).addTo(this.map);
    }

    renderLocation() {
        let locationMarker = L.icon({
            iconUrl:      "leaflet/location.png",
            iconSize:     [24, 24],
            iconAnchor:   [12, 12],
            popupAnchor:  [0, 0]
        });


        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition((position) => {
                L.marker(
                    [position.coords.latitude, position.coords.longitude],
                    {icon: locationMarker}
                ).addTo(this.map);
            });
        }
    }
}


import { UploadClient } from "../uploadcare/index.browser.min.js";

export default class CameraComponent extends HTMLElement {
    constructor() {
        super();

        this.photoData = "";
    }

    connectedCallback() {
        this.innerHTML = `
        <div class="camera">
            <video id="video">Video stream not available.</video>
            <button id="startbutton">Take photo</button>
            <button id="sendbutton">Send photo</button>
        </div>
        <canvas id="canvas"></canvas>
        `;

        window.addEventListener("load", () => {
            this.startup();
        }, false);
    }

    async sendpicture() {
        const blob = await (await fetch(this.photoData)).blob();

        const client = new UploadClient({ publicKey: 'cffa35d14b96b9f15679' });

        const fileInfo = await client.uploadFile(blob);
        const cdnUrl = fileInfo.cdnUrl;

        console.log(cdnUrl);
    }

    takepicture(canvas, video, width, height) {
        const context = canvas.getContext("2d");

        if (width && height) {
            canvas.width = width;
            canvas.height = height;
            context.drawImage(video, 0, 0, width, height);

            this.photoData = canvas.toDataURL("image/png");
        } else {
            this.clearphoto(canvas);
        }
    }

    clearphoto(canvas) {
        const context = canvas.getContext("2d");

        context.fillStyle = "#AAA";
        context.fillRect(0, 0, canvas.width, canvas.height);

        this.photoData = canvas.toDataURL("image/png");
    }

    startup() {
        let streaming = false;
        const width = 320; // We will scale the photo width to this
        let height = 0; // This will be computed based on the input stream

        let video = document.getElementById("video");
        let canvas = document.getElementById("canvas");
        let startbutton = document.getElementById("startbutton");
        let sendbutton = document.getElementById("sendbutton");

        navigator.mediaDevices
            .getUserMedia({ video: true, audio: false })
            .then((stream) => {
                video.srcObject = stream;
                video.play();
            })
            .catch((err) => {
                console.error(`An error occurred: ${err}`);
            });

        video.addEventListener(
            "canplay",
            () => {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth / width);

                    // Firefox currently has a bug where the height can't be read from
                    // the video, so we will make assumptions if this happens.

                    if (isNaN(height)) {
                        height = width / (4 / 3);
                    }

                    video.setAttribute("width", width);
                    video.setAttribute("height", height);
                    canvas.setAttribute("width", width);
                    canvas.setAttribute("height", height);
                    streaming = true;
                }
            },
            false
        );

        startbutton.addEventListener(
            "click",
            (ev) => {
                ev.preventDefault();
                this.takepicture(canvas, video, width, height);
            },
            false
        );

        sendbutton.addEventListener(
            "click",
            (ev) => {
                ev.preventDefault();
                this.sendpicture();
            },
            false
        );

        this.clearphoto(canvas);
    }
}

the camera is not showing up on the page i've tested it on other pages but on the map page it simply does not tell me why it isnt working