<script src="<?= getBaseUrl() ?>assets/plugins/jquery/jquery.min.js"></script>
<script src="<?= getBaseUrl() ?>assets/js/paho-mqtt/paho-mqtt.js"></script>
<script src="<?= getBaseUrl() ?>assets/js/mqtt-connect.js"></script>
<!-- Content Header (Page header) -->
<?php App\Controllers\BackendController::createService()->showBreadCrumbs( $arrmixBreadCrumbData ) ?>
<!-- /.content-header -->

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Small boxes (Stat box) -->
        <div class="js-show-alert-message">
            <?php App\Controllers\BackendController::createService()->showAlertMessage( $arrmixFlashData ) ?>
        </div>
        <div class="row">
            <div class="col-12">
                <div class="card card-default">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-8">
                                <label class="control-label">Status:-  &nbsp;</label>
                                <span id="js-mqtt-status"><small class="badge badge-danger">Offline</small></span>
                            </div>
                            <?php if( true == $boolIsTempConfigFilePresent ) { ?>
                                <div class="col-4">
                                    <div class=" row">
                                        <div class="col-sm-8"></div>
                                        <!-- <label class="col-sm-3 col-form-label">Send Data: &nbsp;</label> -->
                                        <div class="col-sm-4">
                                            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#js-modal-update-config" >
                                                <i class="fas fa-sync"></i> &nbsp; Update Config
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>    
                        </div>
                    </div>    
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-6">
                <div class="card card-default">
                    <div class="card-header">
                        <h3 class="card-title"><span class="text-danger"><i class="fas fa-server"></i> &nbsp; CPU Utlilization</span></h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" id="js-refresh-cpu-data">
                                <i class="fas fa-sync" id="js-refresh-cpu-data-icon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-hover text-nowrap">
                            <tbody>
                                <tr>
                                    <td>User</td>
                                    <td id="js-cpu-user">Loading...</td>
                                </tr>
                                <tr>
                                    <td>Kernel</td>
                                    <td id="js-cpu-kernel">Loading...</td>
                                </tr>
                                <tr>
                                    <td>Idle</td>
                                    <td id="js-cpu-idle">Loading...</td>
                                </tr>
                                <tr>
                                    <td>IO</td>
                                    <td id="js-cpu-io">Loading...</td>
                                </tr>
                                <tr>
                                    <td>Temperature</td>
                                    <td id="js-cpu-temperature">Loading...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-6">
                <div class="card card-default">
                    <div class="card-header">
                        <h3 class="card-title"><span class="text-primary"><i class="fas fa-memory"></i> &nbsp; Memory Utlilization</span></h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" id="js-refresh-memory-data">
                                <i class="fas fa-sync" id="js-refresh-memory-data-icon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-hover text-nowrap">
                            <tbody>
                                <tr>
                                    <td>Free Memory</td>
                                    <td id="js-memory-free">Loading...</td>
                                </tr>
                                <tr>
                                    <td>Occupied Memory</td>
                                    <td id="js-memory-occupied">Loading...</td>
                                </tr>
                                <tr>
                                    <td>Free Storage</td>
                                    <td id="js-storage-free">Loading...</td>
                                </tr>
                                <tr>
                                    <td>Occupied Storage</td>
                                    <td id="js-storage-occupied">Loading...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-3">
                <div class="card card-default">
                    <div class="card-header">
                        <h3 class="card-title"><span class="text-success"> <i class="fas fa-signal"></i> &nbsp; Device Status</span></h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" id="js-refresh-device-status-data">
                                <i class="fas fa-sync" id="js-refresh-device-status-data-icon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">System: &nbsp;</label>
                                <span id="js-system-name">Loading...</span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">FW Version: &nbsp;</label>
                                <span id="js-firmare-version">Loading...</span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">HW Version: &nbsp;</label>
                                <span id="js-hardware-version">Loading...</span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">ETH-1 Link: &nbsp;</label>
                                <span id="js-eth1-link">Loading...</span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">ETH-2 Link: &nbsp;</label>
                                <span id="js-eth2-link">Loading...</span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">COM Port: &nbsp;</label>
                                <span id="js-com-port">Loading...</span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">RSTP: &nbsp;</label>
                                <span class="badge badge-<?= ( SPT_MODE_ENABLED ==  $arrmixDeviceConfigJsonFileData['spt_enable'] ) ? 'success' : 'danger' ?>"><?= ( SPT_MODE_ENABLED ==  $arrmixDeviceConfigJsonFileData['spt_enable'] ) ? 'Enabled' : 'Disabled' ?></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Device Mode: &nbsp;</label>
                                <span><?= ( DEVICE_MODE_CONVERTER == $arrmixDeviceConfigJsonFileData['dev_mode'] ) ? 'Converter' : 'Gateway' ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-3">
                <div class="card card-default">
                    <div class="card-header">
                        <h3 class="card-title"><span class="text-info"><i class="fas fa-ethernet"></i> &nbsp; ETH-1</span></h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Mode: &nbsp;</label>
                                <span><?= ( EHT_MODE_STATIC == $arrmixDeviceConfigJsonFileData['eth1']['mode'] ) ? 'Static' : 'DHCP' ?></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">IP: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['eth1']['ip'] ?></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Subnet Mask: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['eth1']['mask'] ?></span>
                            </div>
                        </div>   
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Default Gateway: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['eth1']['gatw'] ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-3">
                <div class="card card-default">
                    <div class="card-header">
                        <h3 class="card-title"><span class="text-info"><i class="fas fa-ethernet"></i> &nbsp; ETH-2</span></h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Mode: &nbsp;</label>
                                <span><?= ( EHT_MODE_STATIC == $arrmixDeviceConfigJsonFileData['eth2']['mode'] ) ? 'Static' : 'DHCP' ?></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">IP: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['eth2']['ip'] ?></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Subnet Mask: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['eth2']['mask'] ?></span>
                            </div>
                        </div>   
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Default Gateway: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['eth2']['gatw'] ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-3">
                <div class="card card-default">
                    <div class="card-header">
                        <h3 class="card-title"><span class="text-warning"><i class="fas fa-teeth"></i> &nbsp; COM Port</span></h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Baud Rate: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['rs485']['br'] ?></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Parity Bits: &nbsp;</label>
                                <span><?= getParityBitsName( $arrmixDeviceConfigJsonFileData['rs485']['par_bit'] ) ?></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Data Bit: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['rs485']['data_bit'] ?></span>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-12 form-group">
                                <label class="control-label">Stop Bit: &nbsp;</label>
                                <span><?= $arrmixDeviceConfigJsonFileData['rs485']['stop_bit'] ?></span>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>
    </div><!-- /.container-fluid -->
</section>
<!-- /.content -->

<!-- Modal -->
<div class="modal fade" id="js-modal-update-config" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><b>Update Config</b></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                The latest configuration has been updated. Please choose the appropriate action below.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-success js-modal-button-update-config" id="js-send-config-data" data-toggle="tooltip" data-placement="top" title="This will push the latest configuration to the devices.">
                    <i class="fas fa-share-square"></i> &nbsp; Submit Config
                </button>
                <button type="button" class="btn btn-outline-danger js-modal-button-update-config" id="js-reset-config-data" data-toggle="tooltip" data-placement="top" title="This will revert all the changes that you have recently made.">
                    <i class="fas fa-retweet"></i> &nbsp; Reset Config
                </button>
            </div>
        </div>
    </div>
</div>

<script>

    $( document ).ready( function () {

        initMqtt();

        setTimeout(function() {
            sendCommandToGetCpuMemoryUtilization();
            sendCommandToGetDeviceStatus();    
        }, 2000 ); 

        $( '#js-refresh-cpu-data' ).on( 'click', function() { 

            $( '#js-refresh-cpu-data-icon' ).addClass( 'fa-spin' );
            sendCommandToGetCpuMemoryUtilization();
        } );
        
        $( '#js-refresh-memory-data' ).on( 'click', function() { 

            $( '#js-refresh-memory-data-icon' ).addClass( 'fa-spin' );
            sendCommandToGetCpuMemoryUtilization();
        } );
        
        $( '#js-refresh-device-status-data' ).on( 'click', function() { 

            $( '#js-refresh-device-status-data-icon' ).addClass( 'fa-spin' );
            sendCommandToGetDeviceStatus();
        } );

        $( '#js-send-config-data' ).on( 'click', function() {

            $( '#js-modal-update-config' ).modal( 'hide' );

            $( this ).prop( 'disabled', true );

            $.ajax({
                type: "POST",
                url: "<?= getBaseUrl(); ?>" + "dashboard/send-config-data",
                dataType: 'json',
                success: function( objResponseData ) {
                    
                    console.log( objResponseData );
                    $( '.js-modal-button-update-config' ).prop( 'disabled', false );
                    
                    if( true == objResponseData.status ) {

                        showAlertMessage( 'success', objResponseData.message );
                        
                        setTimeout( function(){ 
                            location.reload();
                        }, 2000);
                    } else {
                        showAlertMessage( 'danger', objResponseData.message );
                    }
                }
            });
        });

        $( '#js-reset-config-data' ).on( 'click', function() {

            $( '#js-modal-update-config' ).modal( 'hide' );

            $( this ).prop( 'disabled', true );

            $.ajax({
                type: "POST",
                url: "<?= getBaseUrl(); ?>" + "dashboard/reset-config-data",
                dataType: 'json',
                success: function( objResponseData ) {
                    
                    console.log( objResponseData );
                    $( '.js-modal-button-update-config' ).prop( 'disabled', false );
                    
                    if( true == objResponseData.status ) {

                        showAlertMessage( 'success', objResponseData.message );
                        
                        setTimeout( function(){ 
                            location.reload();
                        }, 1000);
                    } else {
                        showAlertMessage( 'danger', objResponseData.message );
                    }
                }
            });
        });
    });
    
    function processMessage( objMessagePayload ) {

        console.log( 'Processing Message Payload.' );
        console.log(  objMessagePayload );
        
        objMessagePayload = JSON.parse( objMessagePayload );
        
        var intResponseCode = objMessagePayload.resp_of;

        switch( intResponseCode ) {
            case 1000:
                updateCpuMemoryInfo( objMessagePayload.data );
                break;
            
            case 1001:
                updateDeviceStatusInfo( objMessagePayload.data );
                break;
            
            case 1008:
                showConfigResponse( objMessagePayload.status );    
            
            default:
                console.log( 'Unable to update UI for giving response code : ' + intResponseCode );
                break;
        }

        return true;
    }

    function showConfigResponse( intStatus ) {

        switch( intStatus ) {
            case 200:
                showAlertMessage( 'success', 'Your configuration is processing. Please wait for system reboot.' );
                break;
            
            case 301:
            case 401:
                showAlertMessage( 'danger', 'Fail to set your configuration. Please try again.' );
                break;    
            
            default:
                showAlertMessage( 'warning', 'Unable to get valid response.' );
                break;    
        }
    }

    function updateCpuMemoryInfo( objCpuMemoryData ) {

        $( '#js-refresh-cpu-data-icon' ).removeClass( 'fa-spin' ); 

        $( '#js-refresh-memory-data-icon' ).removeClass( 'fa-spin' ); 

        $( '#js-cpu-user' ).html( '<span class="badge bg-warning ">' + objCpuMemoryData.user + '</span>' );
        $( '#js-cpu-kernel' ).html( '<span class="badge bg-primary ">' + objCpuMemoryData.syst + '</span>' );
        $( '#js-cpu-idle' ).html( '<span class="badge bg-success ">' + objCpuMemoryData.idle + '</span>' );
        $( '#js-cpu-io' ).html( '<span class="badge bg-info ">' + objCpuMemoryData.io + '</span>' );
        $( '#js-cpu-temperature' ).html( '<span class="badge bg-secondary ">' + objCpuMemoryData.temp + '</span>' );

        $( '#js-memory-free' ).html( '<span class="badge bg-success ">' + objCpuMemoryData.memfr + '</span>' );
        $( '#js-memory-occupied' ).html( '<span class="badge bg-info ">' + objCpuMemoryData.memoc + '</span>' );
        $( '#js-storage-free' ).html( '<span class="badge bg-success ">' + objCpuMemoryData.storfr + '</span>' );
        $( '#js-storage-occupied' ).html( '<span class="badge bg-info ">' + objCpuMemoryData.storoc + '</span>' );

        return true;
    }

    function updateDeviceStatusInfo( objDeviceStatusData ) {
        
        $( '#js-refresh-device-status-data-icon' ).removeClass( 'fa-spin' ); 

        $( '#js-system-name' ).html( objDeviceStatusData.d_name );
        $( '#js-firmare-version' ).html( objDeviceStatusData.fr_ver );
        $( '#js-hardware-version' ).html( objDeviceStatusData.hr_ver );

        if( 1 == objDeviceStatusData.eth1St ) {
            $( '#js-eth1-link' ).html( '<span class="badge bg-success">Up</span>' );
        } else {
            $( '#js-eth1-link' ).html( '<span class="badge bg-danger">Down</span>' );
        }

        if( 1 == objDeviceStatusData.eth2St ) {
            $( '#js-eth2-link' ).html( '<span class="badge bg-success">Up</span>' );
        } else {
            $( '#js-eth2-link' ).html( '<span class="badge bg-danger">Down</span>' );
        }        

        if( 1 == objDeviceStatusData.rs485St ) {
            $( '#js-com-port' ).html( '<span class="badge bg-success">Up</span>' );
        } else {
            $( '#js-com-port' ).html( '<span class="badge bg-danger">Down</span>' );
        }        

        return true;
    }

    function sendCommandToGetCpuMemoryUtilization() {
        var objPayload = {
            "method": "cmd",
            "msg_id": 1000
        };

        publishMessage( JSON.stringify( objPayload ) );
    }

    function sendCommandToGetDeviceStatus() {
        var objPayload = {
            "method": "cmd",
            "msg_id": 1001
        };

        publishMessage( JSON.stringify( objPayload ) );
    }

    function onConnect() {
        console.log( "On Connect" );
        objMqttclient.subscribe( SUBSCRIBE_TOPIC );

        $( '#js-mqtt-status' ).html( '<small class="badge badge-success">Online</small>' );
    }
</script>