import {
    tiObj,
    checkTotal,
    updateTotals
} from "./generic.js"

import {resetFloors} from "./pdp-generic.js"

let calculationInfo = $('#info-tile-calculation');
let calculationContent = $('#tile-calculation-content');
let tileEsimateMeasurement = $('#open-tile-estimation_measurement');
let quantityInput = '.ti-total-area__input-quantity';
let scrollDelay = 500;
let calcWrapper = $(".pdp-price__calculator-wrapper");
let bannerHeight = 0;
let unitSelect = $(".unit-selection");
let unitSmall,
    unitBig;
if ($('.sticky-wrapper').length) {
    bannerHeight = $('.sticky-wrapper').eq(0).height();
}


calcWrapper.on('click', scrollToCalculator);
tileEsimateMeasurement.on('click', estimateMeasurement);

function scrollToCalculator(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: ($(calculationInfo).offset().top - bannerHeight)
    }, scrollDelay);
    calculationContent.css('display', 'block');
    calculationInfo.removeClass('accordion_collapsed');
}

function estimateMeasurement(e) {
    e.preventDefault();
    let context;

    if ($(this).closest('.fi').length) {
        context = $(this).closest('.fi');
        unitSmall = '.ti-unit_small';
        unitBig = '.ti-unit_big';
    } else if ($(this).closest('.ti').length) {
        context = $(this).closest('.ti');
        unitSmall = '.ti-unit_small';
        unitBig = '.ti-unit_big';
    }

    if (checkTotal(context) === true) {
        context.find('#ti_total-area').removeClass('ti__floors-invalid');

        $('#info-tile-estimation').removeClass('accordion_collapsed');
        $('#tile-estimation-content').show();

        $('#info-tile-calculation').addClass('accordion_collapsed');
        $('#tile-calculation-content').hide();

        resetCalculator(context);

    } else {
        tiObj.system.notification1 = Wick.Notification.show({
            text: `You need to add a wall/floor area or enter a total area of at least ${tiObj.measure.minMeasure} square ${tiObj.measure.measure} to continue to the next step of your estimate`,
            container: $(this).parents('.ti__step').find('.ti__error'),
            type: 'error',
            noScrolling: true,
        });

        context.find('#ti_total-area').addClass('ti__floors-invalid');
    }
}

function resetCalculator(context) {
    resetFloors(tiObj.system.floors);
    context.find('.ti-floor').not('.ti-floor:first').remove();
    tiObj.system.floors = $('.ti-floor');
    context.find('.ti-total-area__input-total').val('');
    updateTotals(context);
    context.find(quantityInput).val('');
    unitSelect.val('metres');

    context.find(unitSmall).html('m');
    context.find(unitBig).html('M');
    tiObj.measure.minMeasure = '5.0';
    tiObj.measure.measure = 'metres';
}

export {scrollToCalculator, estimateMeasurement, resetCalculator, bannerHeight, scrollDelay}
