/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  Script:   data-manager.js     *        v:5.0.0
  Author:   Neil Thomas         *   October 2025
  Original: N Thomas 2025-08-02 15:00:06
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  Last Ed:  2025-10-01 15:31:42
  Role:   Provide scripts to manage cmx data
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

let setOptions= function( options ) {
    //  Show / Hide Apparent / FeelsLike data
    if( options.useApparent === '1' ) {
        $('[data-cmx-Apparent]').removeClass('w3-hide');
        $('[data-cmx-FeelsLike]').addClass('w3-hide');
    } else {
        $('[data-cmx-Apparent]').addClass('w3-hide');
        $('[data-cmx-FeelsLike]').removeClass('w3-hide');
    }

    //  Show / hide ALL solar data
    if( options.showSolar === '0' && options.showUV === '0'){
        $('[data-cmx-NoSolar]').addClass('w3-hide');
    } else {
        $('[data-cmx-NoSolar]').removeClass('w3-hide');
        // Show ~ Hide 'Solar' elements
        if( options.showSolar === '1' ) {
            $('[data-cmx-Solar]').removeClass('w3-hide');
        } else {
            $('[data-cmx-Solar]').addClass('w3-hide');
            $('[data-cmx-SolarGauge]').addClass( 'w3-hide' );
        }

        // Show ~ Hide 'UV' elements
        if( options.showUV === '1' ){
            $('[data-cmx-UV]').removeClass('w3-hide');
        } else {
            $('[data-cmx-UVGauge]').addClass('w3-hide');
            $('[data-cmx-UV]').addClass('w3-hide');
        }
    }
    if( options.showSnow === '1') {
        $('[data-cmx-Snow]').removeClass('w3-hide');
    } else {
        $('[data-cmx-Snow]').addClass('w3-hide');
    }
};

let getPageData = function( resolve, reject)  {
    var dataPath = cmxConfig.DataPath + '/';
    var SnowDataAvailable;
    //  Get snow availability
    $.getJSON( dataPath + 'availabledata.json', function( json ){
        SnowDataAvailable = json.Snow;
    });
    $.getJSON( dataPath + 'websitedata.json?_=' + Date.now(), function(  json ){
        let pageName = window.location.href.split('/').pop().split('.')[0];
        if( activePages.indexOf( pageName ) >= 0 || pageName == '') {
            setTimeout( function() {
                getPageData( null, null );
            }, 60 * 1000);
        }

        cmxData = json ;

        //  Adjust header values
        if(! $(document).prop('title').includes(cmxData.location)) {
            $(document).prop('title', $(document).prop('title') + ' @ ' + cmxData.location);
        }
        $('meta[name=description]').attr('content', cmxData.location + ' weather data');
        $('meta[name=keywords]').attr('content', $('meta[name=keywords]').attr('content') + ', ' + cmxData.location);

        if( initialLoad ) {
            $.getScript( cmxConfig.Menu, function() {
                createMenus( cmxConfig.Custom.StandardMenu, menuSrc ); // Revised system
            });
            initialLoad = false;
        }

        setOptions( cmxData.options );
    
        //  Show ~ Hide 'current conditions' element
        if( cmxData.currcond != '' ) {
            $('[data-cmxCurrCond]').removeClass('w3-hide');
        } else {
            $('[data-cmxCurrCond]').addClass('w3-hide');
        }
        
        //	Add formatted LastRainTime tag
        var rd = new Date( cmxData.LastRainTipISO );
        var LastRainTime = "" + dayName[rd.getDay()] + ' ' + rd.getDate() + ' ' + monthName[rd.getMonth()] + ' ' +rd.getFullYear() + ' @ ' + addLeadingZeros(rd.getHours()) + ':' + addLeadingZeros(rd.getMinutes());
        LastRainTime = addLeadingZeros(rd.getHours()) + ':' + addLeadingZeros(rd.getMinutes()) + ' on ' + dayName[rd.getDay()] + ' ' + rd.getDate() + ' ' + monthName[rd.getMonth()] + ' ' + rd.getFullYear();
        cmxData.LastRainTime = LastRainTime;

        // Update all spans with data-cmxData tags
        $('[data-cmxData]').each( function() {
        this.innerHTML = cmxData[this.dataset.cmxdata];
    });

    if( typeof( cmxData.LightningStrikesToday) == "undefined") {
        $('[data-cmx-NoLightning]').addClass('w3-hide');
    } else {
        if( cmxData.LightningStrikesToday === 0) {
            $('[data-cmx-Lightning]').removeClass('w3-hide');
        } else {
            $('[data-cmx-Lightning]').addClass('w3-hide');
        }
    }

    //  Show / Hide Wet Bulb
    if( typeof( cmxData.wetbulb) == 'undefined') {
        $('[data-cmx-WetBulb]').addClass('w3-hide');
    } else {
        $('[data-cmx-WetBulb').removeClass('w3-hide');
    }

    //  Add the time of the last rainfall
    $('[data-cmxData="LastRainTime"]').text( cmxData.LastRainTime);

    if (null !== resolve) {
        resolve();
    }
        })

    .fail( function( jqxhr, textStatus, error) {
        let err = textStatus + ', ' + error;
        console.log('Data request failed: ' + err );

    if( null !== reject) {
        reject;
    }

    setTimeout( function() {
        getPageData( resolve, reject );
        }, 5000 );
    });
};
