import * as Cart from './modules/cart.js';
import { numberToEuroFormat } from './utils.js';
import { Product } from './elements/product.js';

function clearAddressFields() {
    document.querySelector('#address-components').style.display = "none";
    document.querySelector('#street-number').value = '';
    document.querySelector('#street-number').setAttribute('disabled', true);
    document.querySelector('#route').value = '';
    document.querySelector('#locality').value = '';
    document.querySelector('#postal-code').value = '';
}

function getAddressFiedlValue(addressComponents, $field) {
    let field = addressComponents.find(obj => obj.types.indexOf($field) > -1);
    return field != undefined ? field.long_name : '';
}

const urlBase = document.querySelector('meta[name="url-base"]').getAttribute("content");

let input = document.querySelector("#tel");
let iti = null;
if (input != undefined) {
    iti = window.intlTelInput(input, {
        initialCountry: "de",
        preferredCountries: ["de"],
        geoIpLookup: function (callback) {
            $.get('https://ipinfo.io', function () { }, "jsonp").always(function (resp) {
                let countryCode = (resp && resp.country) ? resp.country : "us";
                callback(countryCode);
            });
        },
        utilsScript: urlBase + "/template/assets/libs/intl-tel-input-17.0.0/js/utils.min.js",
    });
}

async function updateProducts() {
    document.querySelector('#list-products').innerHTML = '';

    let products = await Cart.getItems();

    if (products.length > 0) {

        products.forEach(function (product) {


            let elementProduct = Product(product);

            let productRow = document.createElement('tr');
            productRow.innerHTML = elementProduct;

            document.querySelector('#list-products').append(productRow);

        });

        if (Cart.getTotalPrice() > 0) {
            document.querySelector('#total-checkout-price').text(numberToEuroFormat(Cart.getTotal()));
        } else {
            document.querySelector('#form-section').style.display = "none";
            //$('#list-products').parent().parent().parent().parent().parent().find('.modal-footer').hide();
            //document.querySelector('#total-checkout-price').parentElement.parentElement.parentElement.style.display = "none";
            document.querySelector('#no-products-in-checkout').style.display = "none";
            document.querySelector('#cart-error-in-checkout').style.display = "block";
        }

        document.querySelector('#form-section').style.display = "block";
        //document.querySelector('#list-products').parent().parent().parent().parent().parent().find('.modal-footer').show();
        //document.querySelector('#total-checkout-price').parentElement.parentElement.parentElement.style.display = "block";
        document.querySelector('#no-products-in-checkout').style.display = "none";
        document.querySelector('#cart-error-in-checkout').style.display = "none";
    }
    else {
        document.querySelector('#form-section').style.display = "none";
        //$('#list-products').parent().parent().parent().parent().parent().find('.modal-footer').hide();
        document.querySelector('#total-checkout-price').parentElement.parentElement.parentElement.style.display = "none";
        document.querySelector('#no-products-in-checkout').style.display = "block";
        document.querySelector('#cart-error-in-checkout').style.display = "none";
    }
}

document.addEventListener('DOMContentLoaded', () => {
    updateProducts();
    //document.querySelector("#successful-submitting-form").delay(4000).slideUp(200, function () { $(this).alert('close'); });
    document.querySelector('#checkout').addEventListener("submit", function (event) {
        event.preventDefault();
        let form = $(this);
        getInfoFromSelectedProduct().done(function (response, status) {
            let products = response.contents.map(product => {
                product = getProductInfo(product);
                product = calculatePrice(product);
                return product.quantity + 'x ' + product.title + ' (' + numberToEuroFormat(product.calc_preis) + ')';
            });
            let cart = products.join(" - ") + " - Gesammt: " + numberToEuroFormat(totalPrice);
            $('#ccart').val(cart);
            $('#ctelefon').val(iti.getNumber());
            objProducts = [];
            localStorage.setItem("products", JSON.stringify(objProducts));
            form.unbind('submit').submit();
        });
    });

    document.body.addEventListener('click', async function (event) {
        if (event.target.matches('.btn-remove-product')) {
            if (objProducts.length > 0) {
                $('#form-section').show();
                $('#list-products').parent().parent().parent().parent().parent().find('.modal-footer').show();
                $('#total-checkout-price').parent().parent().parent().show();
                $('#no-products-in-checkout').hide();
            } else {
                $('#form-section').hide();
                $('#list-products').parent().parent().parent().parent().parent().find('.modal-footer').hide();
                $('#total-checkout-price').parent().parent().parent().hide();
                $('#no-products-in-checkout').show();
            }
        }
    });

    document.body.addEventListener('input', async function (event) {
        if (event.target.matches('.select-quantity')) {
            let products = await Cart.getTotalPrice();
            document.querySelector('.js-total-price').innerText = numberToEuroFormat(products);
        }
    });
});

/* 
$(window).on('load', google.maps.event, function () {
    let input = document.getElementById('field_location');
    let options = {
        types: ['address'],
        componentRestrictions: { country: "de" }
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    autocomplete.addListener("place_changed", () => {

        clearAddressFields();

        const place = autocomplete.getPlace();
        if (!place.geometry) return;
        var componentMap = {
            country: 'country',
            locality: 'locality',
            administrative_area_level_1: 'administrative_area_level_1',
            administrative_area_level_2: 'administrative_area_level_2',
            postal_code: 'postal_code',
            route: 'route',
            street_number: 'street_number',
        };
        $('#address-components').show();
        let addressComponents = autocomplete.getPlace().address_components;
        let streetNumber = getAddressFiedlValue(addressComponents, 'street_number');
        if (streetNumber == '') {
            $('#street-number').prop('disabled', false);
            $('#street-number').focus();
        }
        else {
            $('#street-number').prop('disabled', true);
            $('#street-number').val(streetNumber);
        }
        let country = getAddressFiedlValue(addressComponents, 'country');
        let route = getAddressFiedlValue(addressComponents, 'route');
        $('#route').val(route);
        let locality = getAddressFiedlValue(addressComponents, 'locality');
        $('#locality').val(locality);
        let postalCode = getAddressFiedlValue(addressComponents, 'postal_code');
        $('#postal-code').val(postalCode);
        $('#street-number').blur(function () {
            if ($('#street-number').val() == '') $('#street-number').focus();
            else {
                $('#street-number').prop('disabled', true);
                $('#field_location').val(route + ' ' + $('#street-number').val() + ', ' + locality + ', ' + country);
            }
        });
    });
});
*/