$(document).ready(function () {
    let floorInputs,
        closeFloorBtn,
        unitSelect = $('.unit-selection'),
        floors,
        addFloorBtn,
        estimate,
        wastageInput,
        wastageInput1;

    if ($(this).find('.tc-generic').length) {
        floorInputs = '.tc-floor input';
        floors = $('.tc__floors');
        estimate = $('.tc__estimate');
        closeFloorBtn = '.tc-floor__close';
        tiObj.system.floors = $('.tc-floor');
        addFloorBtn = $('.tc-floor__add-floor');
        cloneFloor = $('.tc-floor').eq(0).clone(true);

    } else if ($(this).find('.fi').length || $(this).find('.ti').length) {
        floorInputs = '.ti-floor input';
        floors = $('.ti__floors');
        estimate = $('.ti__estimate');
        closeFloorBtn = '.ti-floor__close';
        tiObj.system.floors = $('.ti-floor');
        addFloorBtn = $('.ti-floor__add-floor');
        cloneFloor = $('.ti-floor').eq(0).clone(true);
        wastageInput = '#wastage';
        wastageInput1 = '#wastage_measurement';

        $(wastageInput).on('change', calculationWastage);
        $(wastageInput1).on('change', calculationWastage);
    }

    unitSelect.on('change', selectUnit);
    floors.on('input', floorInputs, calculateFloors);
    estimate.on('click', closeFloorBtn, closeFloor);
    addFloorBtn.on('click', addFloor);

});

let tiObj = {
    system: {
        floors: $('.ti-floor'),
    },
    startingInfo: {
        sqmPERpack: 1.25,
        pricePERpack: 14.04
    },
    userInfo: {
        minPostPrice: 99.9,
        totalWaste: true,
        postCode: '',
        disposal: false,
        disposalArea: 0,
        tilingOptions: []
    },
    measure: {
        minMeasure: '5.0',
        measure: 'metres',
        measureAbbr: 'M'
    }
};

let cloneFloor;
let warningValue = '.ti__warning-value';
let warningMeasurement = '.ti__warning-measurement';

function selectUnit() {

    if ($(this).closest('.tc-generic').length) {
        const context = $(this).closest('.tc-generic');

        let unitSmallTotalAria = '.tc-unit_small-total-aria',
            unitBigTotalAria = '.tc-unit_big-total-aria',
            unitTileSize = '.tc-unit_tile-size',
            unitDimensionsWall = '.tc-unit_dimensions-wall',
            unitTileSizeSmall = '.tc-unit_tile-size_small',
            unitDimensionsWallSmall = '.tc-unit_dimensions-wall_small';

        switch ($(this).val()) {
            case 'Metres/millimetres':
                context.find(unitTileSizeSmall).html('mm');
                context.find(unitDimensionsWallSmall).html('m');
                context.find(unitDimensionsWall).html('metres');
                context.find(unitTileSize).html('millimetres');
                context.find(unitSmallTotalAria).html('sqm');
                context.find(unitBigTotalAria).html('SQM');
                break;
            case 'Feet/inches':
                context.find(unitTileSizeSmall).html('inches');
                context.find(unitDimensionsWallSmall).html('feet');
                context.find(unitDimensionsWall).html('feet');
                context.find(unitTileSize).html('inches');
                context.find(unitSmallTotalAria).html('sqft');
                context.find(unitBigTotalAria).html('SQFT');
                break;
            default:
                context.find(unitTileSizeSmall).html('mm');
                context.find(unitDimensionsWallSmall).html('m');
                context.find(unitDimensionsWall).html('metres');
                context.find(unitTileSize).html('millimetres');
                context.find(unitSmallTotalAria).html('sqm');
                context.find(unitBigTotalAria).html('SQM');
        }

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

        switch ($(this).val()) {
            case 'feet':
                context.find(unitSmall).html('ft');
                context.find(unitBig).html('FT');
                tiObj.measure.minMeasure = '54.0';
                tiObj.measure.measure = 'feet';
                tiObj.measure.measureAbbr = 'FT';
                break;
            case 'metres':
                context.find(unitSmall).html('m');
                context.find(unitBig).html('M');
                tiObj.measure.minMeasure = '5.0';
                tiObj.measure.measure = 'metres';
                tiObj.measure.measureAbbr = 'M';
                break;
            case 'cm':
                context.find(unitSmall).html('cm');
                context.find(unitBig).html('CM');
                tiObj.measure.minMeasure = '50000.0';
                tiObj.measure.measure = 'cm';
                tiObj.measure.measureAbbr = 'CM';
                break;
            case 'inches':
                context.find(unitSmall).html('in');
                context.find(unitBig).html('IN');
                tiObj.measure.minMeasure = '7750.0';
                tiObj.measure.measure = 'inches';
                tiObj.measure.measureAbbr = 'IN';
                break;
            default:
                context.find(unitSmall).html('m');
                context.find(unitBig).html('M');
                tiObj.measure.minMeasure = '5.0';
                tiObj.measure.measure = 'metres';
                tiObj.measure.measureAbbr = 'M';
        }

        context.find(warningValue).text(tiObj.measure.minMeasure);
        context.find(warningMeasurement).text('tiObj.measure.measureAbbr');
        $('.ti__header-unit').text(tiObj.measure.measure);

        if ($('#ti_total-area').val() > 0 || $('#ti_total-area-calc').val() > 0) {
            checkTotal(context)
        }

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

        switch ($(this).val()) {
            case 'feet':
                context.find(fiUnit).html('ft');
                context.find(unitSmall).html('ft');
                context.find(unitBig).html('ft');
                tiObj.measure.minMeasure = '54.0';
                tiObj.measure.measure = 'feet';
                tiObj.measure.measureAbbr = 'ft';
                break;
            case 'metres':
                context.find(fiUnit).html('m');
                context.find(unitSmall).html('m');
                context.find(unitBig).html('m');
                tiObj.measure.minMeasure = '5.0';
                tiObj.measure.measure = 'metres';
                tiObj.measure.measureAbbr = 'm';
                break;
            case 'cm':
                context.find(fiUnit).html('cm');
                context.find(unitSmall).html('cm');
                context.find(unitBig).html('cm');
                tiObj.measure.minMeasure = '50000.0';
                tiObj.measure.measure = 'cm';
                tiObj.measure.measureAbbr = 'cm';
                break;
            case 'inches':
                context.find(fiUnit).html('in');
                context.find(unitSmall).html('in');
                context.find(unitBig).html('in');
                tiObj.measure.minMeasure = '7750.0';
                tiObj.measure.measure = 'inches';
                tiObj.measure.measureAbbr = 'in';
                break;
            default:
                context.find(fiUnit).html('m');
                context.find(unitSmall).html('m');
                context.find(unitBig).html('m');
                tiObj.measure.minMeasure = '5.0';
                tiObj.measure.measure = 'metres';
                tiObj.measure.measureAbbr = 'm';
        }

        context.find(warningValue).text(tiObj.measure.minMeasure);
        context.find(warningMeasurement).text(tiObj.measure.measureAbbr);
        $('.ti__header-unit').text(tiObj.measure.measure);

        if ($('#ti_total-area').val() > 0 || $('#ti_total-area-calc').val() > 0) {
            checkTotal(context)
        }
    }

}

function calculateFloors() {
    let x, y;
    const context = $(this).closest('.ti__estimate');
    if ($(this).closest('.tc-generic').length) {
        x = $(this).closest('.tc-floor').find('input');
        y = $(this).closest('.tc-floor').find('.tc-floor__result-value');
    } else if ($(this).closest('.fi').length || $(this).closest('.ti').length) {
        x = $(this).closest('.ti-floor').find('input');
        y = $(this).closest('.ti-floor').find('.ti-floor__result-value');
    }

    let x1 = x.eq(0).val(),
        x2 = x.eq(1).val(),
        area = (x1 * x2);

    if (area !== 0) {
        y.text(+area.toFixed(2));
    } else {
        y.text(0);
    }

    updateFloorArea(context, this);
}

function closeFloor() {
    const context = $(this).closest('.ti__estimate');

    if ($(this).closest('.tc-generic').length) {
        $(this).closest('.tc-floor').remove();
        tiObj.system.floors = $('.tc-floor');

    } else if ($(this).closest('.fi').length || $(this).closest('.ti').length) {
        $(this).closest('.ti-floor').remove();
        tiObj.system.floors = $('.ti-floor');
    }

    let fakeEl = $('.ti-floor input')[0];
    updateFloorArea(context, fakeEl);
}


function addFloor() {
    const context = $(this).closest('.ti__estimate');
    $(this).before(cloneFloor.clone(true));
    if ($(this).closest('.tc-generic').length) {
        tiObj.system.floors = $('.tc-floor');
    } else if ($(this).closest('.fi').length || $(this).closest('.ti').length) {
        tiObj.system.floors = $('.ti-floor');
    }

    updateFloorArea(context, this);
}

function updateFloorArea(context, currentEl) {
    let results,
        resultValue = 0;
    if ($(currentEl).closest('.tc-generic').length) {
        results = $('.tc-floor__result-value .wall-floor');
    } else if ($(currentEl).closest('.fi').length || $(currentEl).closest('.ti').length) {
        results = context.find('.ti-floor__result-value');
    }

    for (let i = 0; i < tiObj.system.floors.length; i++) {
        if ($(results[i]).text() === '-') {
            continue
        }
        resultValue += +$(results[i]).text();
    }
    if (resultValue > 0) {
        context.find('.ti-total-area__input-total').val(resultValue);
        checkTotal(context);
        updateTotals(context);
    }
}

function checkTotal(context) {
    if (!context.hasClass('tile-measurement')) {
        let inputValue = parseInt(context.find('.ti-total-area__input-total').val());
        if (inputValue < +tiObj.measure.minMeasure || isNaN(inputValue)) {
            context.find('.ti__total').addClass('less-then-5');
        } else {
            context.find('.ti__total').removeClass('less-then-5');
            context.find('.ti__floors').removeClass('ti__floors-invalid');
            if (tiObj.system.notification1) {
                tiObj.system.notification1.hide();
            }
        }
        return !(inputValue < +tiObj.measure.minMeasure || isNaN(inputValue));
    } else {
        if (tiObj.system.notification1) {
            tiObj.system.notification1.hide();
        }
        context.find('.ti__total').removeClass('less-then-5');
        context.find('.ti__floors').removeClass('ti__floors-invalid');
    }
}

function updateTotals(context) {
    let wastage = 1.1;
    if (tiObj.userInfo.totalWaste === false) {
        wastage = 1;
    }
    let quantityInput = '.ti-total-area__input-quantity';
    let inputValue = context.find('.ti-total-area__input-total').val() * wastage;
    tiObj.userInfo.totalArea = +(inputValue / wastage).toFixed(2);
    tiObj.userInfo.totalWasteArea = +inputValue.toFixed(2);
    context.find('.ti-total-area__wastage-value').text(tiObj.userInfo.totalWasteArea);
    context.find('.ti-total-area__row-cost').text(tiObj.userInfo.totalWasteArea);
    tiObj.userInfo.packs = Math.ceil(inputValue / tiObj.startingInfo.sqmPERpack);
    context.find(quantityInput).val(tiObj.userInfo.packs);
    $('.ti__cost_removal-input input').val(+tiObj.userInfo.totalArea);
    $('.ti__cost_removal-value').text(+tiObj.userInfo.totalArea);
    context.find('.ti-total-area__row-number').text(tiObj.userInfo.packs);
    context.find('.ti-total-area__total-value').text('£' + (tiObj.userInfo.packs * tiObj.startingInfo.pricePERpack).toFixed(2));
    $('.ti__overview-price_total-value').text('£' + (tiObj.userInfo.packs * tiObj.startingInfo.pricePERpack + tiObj.userInfo.minPostPrice).toFixed(2) + '*');
}

function calculationWastage() {
    const context = $(this).closest('.ti__estimate'),
        notificationAccordion = '.ti-total-area__detail-name_accordion';

    if ($(this).attr('checked') === 'checked') {
        $(this).removeAttr('checked');
        tiObj.userInfo.totalWaste = false;
        if (context.find(notificationAccordion).hasClass('collapsed')) {
            context.find(notificationAccordion).click();
        }
    } else {
        $(this).attr('checked', 'checked');
        tiObj.userInfo.totalWaste = true;
    }
    context.find('.ti__total').toggleClass('ti__total-waste');
    updateTotals(context);
}

export {
    tiObj,
    selectUnit,
    calculateFloors,
    updateFloorArea,
    closeFloor,
    addFloor,
    checkTotal,
    updateTotals,
    calculationWastage
}
