import NotifyKhazanah from './Class/SubscribePusher.js';
let channel = 'notify-deposit';
let event = 'deposit-event';
let apikey = window.apikey;

const Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 5000,
    timerProgressBar: true,
    didOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer)
        toast.addEventListener('mouseleave', Swal.resumeTimer)
    }
})

const notify = new NotifyKhazanah(channel,event,apikey);
notify.channel_subscribe((data) => {
    console.log(data);
    Toast.fire({
        icon: 'info',
        title: 'Permohonan Kelulusan Wang Tunai Teller!'
    });
    const currentPath = window.location.pathname;
    
    if(window.kodcaw == data.cawangan){
        if (currentPath === "/home") {
            notify_main();
        } else if (currentPath === "/menu") {
            notify_khazanah_main();
        }else if(currentPath === '/pendahuluan'){
            notify_pendahuluan();
        }else if(currentPath === '/serahan'){
            notify_serahan();
        }
    }

});

let requestApi = (url, method, datarequest, callback) => {
    $.ajax({
        method: method,
        url: url,
        data: datarequest,
        success: function(data) {
            callback(data);
        },
        error: function(xhRequest, ajaxOptions, thrownError) {
            console.error("Request failed:", xhRequest, thrownError);
        }
    });
};


let notify_main = () =>{
    const button = document.getElementById("btn-khazanah");

    if(!button){
        return;
    }

    button.classList.add('btn-danger');
}

let notify_khazanah_main = () =>{
    requestApi(window.api + '/api/requestTeller/get/' + window.kodcaw,"GET",{}, (response) =>{
        let countModal = 0;
        let countSerahan = 0;

        response.forEach((req) => {
            if (req.modal !== 0) {
                countModal++;
            } else if (req.serahan !== 0) {
                countSerahan++;
            }
        });

        let btn_serahan = document.getElementById('btn-ser');
        let btn_pendahuluan = document.getElementById('btn-pend');
        let span_element_ser = btn_serahan.querySelector('span');
        let span_element_pend = btn_pendahuluan.querySelector('span');

        if(!btn_serahan.classList.contains('btn-danger') && countSerahan > 0){
            btn_serahan.classList.add('btn-danger');
            span_element_ser.innerText = countSerahan;
        }
        
        if(!btn_pendahuluan.classList.contains('btn-danger') && countModal > 0){
            btn_pendahuluan.classList.add('btn-danger');
            span_element_pend.innerText = countModal;
        }

    });
}

let notify_pendahuluan = () =>{
    timer_reload();
}

let notify_serahan = () =>{
    timer_reload();
}

let timer_reload = () =>{
    setTimeout(() => {
        window.location.reload();
    }, 3000);
}
