<script type="text/javascript">
    var customspinner = '<div class="custom-lds-ring"><div></div><div></div><div></div>';

    $(function() {
        reconfigure();
    });


    function serializeInput(id_form)
    {
        var dt = new FormData();
        var t = $('#'+id_form).find("select, textarea, input");
        $.each(t, function(i, v) {
            if($(this).prop('disabled') != true)
            {
                var name;
                if($(this).attr('id').length > 0)
                {
                    name = $(this).attr('id');
                }else if($(this).attr('name').length > 0)
                {
                    name = $(this).attr('name');
                }

                var val = $(this).val();
                dt.append(name, val);
            }
        });

        return dt;
    }


    $(document).ajaxError(function(event, request, settings){
        req_token();
    });

    $(document).ajaxSend(function(event, request, settings){
        if(settings.hasOwnProperty('headers') === false)
        {
            set_header();
        }
    });

    <?php
    // IF PRODUCTION HIDE TABEL ERROR
    if(ENVIRONMENT == 'production'){
    ?>
            if (jQuery().DataTable) {
                $.fn.dataTable.ext.errMode = function( settings, techNote, message ){
                    // alert('Terjadi gangguan saat mengambil data, halaman ini akan dimuat ulang dalam 3 detik setelah anda menekan tombol "OK"');
                    setTimeout(function(){
                        location.reload();
                    }, 500);
                };
            }
    <?php } ?>

    $(document).ajaxComplete(function( event, request, settings ) {
        if(typeof request.responseJSON !== 'undefined'){
            reconfigure(request);
        }
        var tabel = $('div.dataTables_scrollBody > table');
        if(tabel.length > 0){
            var id_tabel = tabel.attr('id');
            if(typeof request.responseJSON !== 'undefined'){
                if(request.responseJSON.success == true){
                    if ( $.fn.DataTable.isDataTable( '#'+id_tabel ) ) {
                        if(request.responseJSON.type == "save"){

                            if($('#'+id_tabel).DataTable().state() != null)
                            {
                                $('#'+id_tabel).DataTable().ajax.reload(null,false);
                            }else{
                                console.log('tes');
                                $('#'+id_tabel).DataTable().ajax.reload(null,false);
                            }

                        }else{
                            // table.ajax.reload(callback, resetPaging)
                            $('#'+id_tabel).DataTable().ajax.reload(null,false);
                        }
                    }
                }
            }

        }
    });

    function reconfigure(data = null){
        if(data != null){
            $("meta[name=csrf-token]").attr('content', data.responseJSON.csrf_token);
        }

        set_header();
        refresh_token();
    }

    function set_header()
    {
        $.ajaxSetup({
            headers: {
                'Csrf-Token':  $('meta[name="csrf-token"]').attr('content')
            }
        });
    }

    // function reconfigure(data = null){
    //     if(data != null){
    //         $("meta[name=csrf-token]").attr('content', data.responseJSON.csrf_token);
    //     }

    //     $.ajaxSetup({
    //         headers: {
    //             'Csrf-Token':  $('meta[name="csrf-token"]').attr('content')
    //         }
    //     });


    // }

    function req_token()
        {
            $.get('<?php echo route('new.token.req') ?>', function(result){
                var json = $.parseJSON(result);

                if(json.status)
                {
                    $('meta[name="csrf-token"]').attr('content', json.csrf_token);
                    reconfigure();
                }else{
                    location.reload();
                }
            });
        }
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.min.js" ></script>

    <script type="text/javascript">
        var socket = undefined;
        var hostname = window.location.origin ? window.location.origin + '' : window.location.protocol + '/' + window.location.host + '';
        // var socket = io( ':2083/absenku-gss');
        // var socket = io.connect( '<?php echo $this->config->item('socket_server') ?>' );
        syncSocket();

        async function syncSocket() {
          let doPromise = new Promise(function(resolve, reject) {

            $.ajax({
                url: hostname+":2083",
                headers: {'X-Requested-With': 'XMLHttpRequest'},
                xhr: function(){
                    var xhr = $.ajaxSettings.xhr();
                    var setRequestHeader = xhr.setRequestHeader;
                    xhr.setRequestHeader = function(name, value) {
                        if (name == 'Csrf-Token') return;
                        setRequestHeader.call(this, name, value);
                    }
                    return xhr;
                },
                success: function(response){
                    if(response.serverStatus === 'ready')
                    {
                        resolve(response.serverStatus);
                    }else{
                        reject("Error");
                    }
                },
                error: function(err){
                    console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
                }
            });
          });
          await doPromise.then(
                function(value) {runSocket(value);},
                function(error) {runSocket(error);}
            );
        }

        function runSocket(v)
        {
            socket = io(':<?= $this->config->item('socket_port') ?>/<?= $this->config->item('socket_namespace') ?>');

            socket.on('connect', function(){
                socket.emit('connect_users', {'id_karyawan' : '<?= $this->session->userdata("id_karyawan") ?>'});
            });

            socket.on('look-online',function(data){
                // console.log(data);
                // $.each(data.data, function(k,v){
                //     setTimeout(function(){
                //     $('.o-stat-'+k).removeClass('text-muted');
                //     $('.o-stat-'+k).addClass('text-success');
                //     $('.o-stat-'+k).text('Online');
                //     $('.n-'+k).html('<span class="heartbit"></span> <span class="point"></span>');
                //     }, 1000);
                // });
            });

            // socket.emit("izin",{'room': '11'});
            socket.on('receive_notif',function(data){

                if(data.type == 'izin')
                {
                    load_notif_izin();
                }else if(data.type == 'lembur')
                {
                    load_notif_lembur();
                }

                if ($.fn.loadlst) {
                    loadlst(data.type);
                }
                // $('.notif').addClass('show');
                if(typeof data.show_notification != 'undefined' && data.show_notification == true)
                {
                    notifyMe(data.params);
                }
            });

            socket.on('req_token', function(data){
                var c = data._token;
                $('meta[name="csrf-token"]').attr('content', c);
                set_header();
            });

            socket.on('broadcast', function(data){
                console.log(data);
            });

            socket.on('receive_visitor_statistic', function(data){
                // alert2('tes');
                // setVisitorStatistic(data);
                setVisitorStatistic(data);
            });
        }

        function broadcast_visitor_statistik(data){
            if(socket !== undefined)
            {
                socket.emit('broadcast_visitor_statistic', data);
            }
        }

        function refresh_token()
        {
            if(socket !== undefined)
            {
                socket.emit('refresh-token', {'id_karyawan' : '<?= $this->session->userdata("id_karyawan") ?>', '_token' :  $('meta[name="csrf-token"]').attr('content'), 'refresh' : true});
            }
        }

        function cek_soket(){
            if(socket !== undefined)
            {
                socket.emit('test-broadcast', {'a' : 'b', 'c' : 'd', 'room': '<?php echo $room ?>'});
            }
        }

        function disconnect(){
            if(socket !== undefined)
            {
                socket.emit('disconnect_users', {'user': '<?php echo $user ?>', 'room': '<?php echo $room ?>'});
            }
        }
        // const xhr = new XMLHttpRequest();
        // xhr.open("GET", hostname+":2083");
        // xhr.withCredentials = true;
        // xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        // xhr.setRequestHeader("X-Requested-With", "“XMLHttpRequest”");
        // xhr.send();
    </script>
