// Check Status ransaction
window.checkStatusTransaction = (statusCode) => {
    var status = '';
    if (statusCode === 3) {
        status = 'Approved';
    } else if (statusCode === 2) {
        status = 'Rejected';
    } else if (statusCode === 1) {
        status = 'Cancelled';
    } else {
        status = 'Pending';
    }

    return status;
}

//    CONVERT NOMINAL
window.convertNominal = function (code, nominal) {
    var pattern = '!#';
    var symbol = '';
    var separator = '';
    var precision = 0;
    var decimal = ',';

    switch (code) {
        case 'CNY':
            symbol = '¥';
            separator = '.';
            precision = 2;
            break;

        case 'VND':
            symbol = '₫';
            separator = ',';
            precision = 0;
            break;

        case 'MYR':
            symbol = 'MYR';
            separator = '.';
            precision = 2;
            break;

        case 'THB':
            symbol = '฿';
            separator = '.';
            precision = 2;
            break;

        case 'IDR':
            symbol = 'IDR ';
            separator = '.';
            precision = 2;
            break;
            
        case 'USD':
            symbol = 'USD ';
            separator = '.';
            precision = 2;
            break;

        case 'KRW':
            pattern = '# !';
            symbol = ' 원';
            separator = '.';
            precision = 2;
            break;

        default:
            symbol = '';
            separator = '.';
            precision = 2;
            break;
    }

    var format = function format(value) {
        return currency(value, {
            pattern: pattern,
            precision: precision,
            symbol: symbol,
            separator: separator,
            decimal: decimal
        });
    };

    var convert = 0;

    if (nominal) {
        convert = parseFloat(nominal);
    }

    convert = format(convert).format(true);
    return convert;
};
//    END CONVERT NOMINAL

//    CONTENT OPEN
$(document).on('click', '.contentOpen', function () {
    if ($(this).attr('open-href')) {
        var openUrl = $(this).attr('open-href');
        var openType = $(this).attr('open-type');

        if (openType === 'new-tab') {
            window.open(openUrl, '_blank');
        } else if (openType === 'pop-up') {
            openPopupTab(openUrl, '', 1180, 675, openType);
        } else if (openType === 'pop-up-parent') {
            openNewParentTab(openUrl, 'parent tab', 1024, 690, 0, 0, 'yes');
        } else if (openType === 'trigger-function') {
            Function(openUrl)();
        } else {
            window.location.href = openUrl;
        }
    }
});

function openPopupTab(url, params, width, height, name, target = '') {
    var screenLeft = 0,
        screenTop = 0;
    if (!name) name = '';
    if (!width) width = 1060;
    if (!height) height = 665;
    var defaultParams = {};

    if (typeof window.screenLeft !== 'undefined') {
        screenLeft = window.screenLeft;
        screenTop = window.screenTop;
    } else if (typeof window.screenX !== 'undefined') {
        screenLeft = window.screenX;
        screenTop = window.screenY;
    }

    var features_dict = {
        toolbar: 'no',
        location: 'no',
        directories: 'no',
        left: screenLeft + ($(window).width() - width) / 2,
        top: screenTop + ($(window).height() - height) / 2,
        status: 'yes',
        menubar: 'no',
        scrollbars: 'yes',
        resizable: 'no',
        width: width,
        height: height
    };
    features_arr = [];

    for (var k in features_dict) {
        features_arr.push(k + '=' + features_dict[k]);
    }

    features_str = features_arr.join(',');
    var win = window.open(url, name, features_str);

    if (target == '_parent') {
        win = window.open(url, target, name, features_str);
    }
    win.focus();
    return false;
}

function openNewParentTab(url, name, width, height, left, top, scrollbars) {
    window.open(url, name, 'left=' + left + ', top=' + top + ', width=' + width + ', height=' + height + ', scrollbars=' + scrollbars + ', location=no, menubar=no, titlebar=no, hotkeys=no, toolbars=no, status =no, resizable=yes');
}

// GLOBAL ALERT
// must be include izi-toast plugin
window.buzzer = (arg) => {
    iziToast[arg.status]({
        timeout: arg.timeout ?? 3000,
        overlay: arg.overlay ?? true,
        close: arg.close ?? true,
        position: 'topCenter',
        title: '',
        message: arg.msg,
        onClosed: arg.onClosed ?? '',
        buttons: arg.button ?? '',
    });
}

// count down function
window.countdowntime = function (servertime, time, elementId) {
var arrtime = time.split(' ');

time = new Date(arrtime[0]);
time.setHours(arrtime[1].split(':')[0], arrtime[1].split(':')[1]);

servertime = new Date(servertime);
    // Update the count down every 1 second
    let y = 0;
    var x = setInterval(function() {
        y++;
    var now = new Date()
        now.setHours(servertime.getHours(), now.getMinutes());
        var close = time - now;
    // referesh every one hours
    var sec = `${now.getMinutes()}${now.getSeconds()}`;
    if (sec == '01') {
    window.location = window.location.pathname;
    }
        // cek if time bet is close pass time now
        if (time < servertime) {
            time.setDate(servertime.getDate() + 1);
        }
        // check if count down finish count from
        // if (close < 0) {
        // 	time.setDate(servertime.getDate() + 1);
        // }

        // Find the distance between now and the count down date
        var distance = time - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    if (days > 0) {
        hours = hours + 24 * days;
    }

        var h = (hours > 0) ? `${hours}` : 00;
        var m = (minutes > 0) ? `${minutes}` : 00;
        var times = `${h}:${m}:${seconds}`;

    // check if count down finish set to bet CLose
        if (close < 0) {
            (y > 1) ? times = 'BET CLOSED': times
        }

    if ($.isArray(elementId)) {
    document.querySelector(elementId[0]).innerHTML = `${h}`
    document.querySelector(elementId[1]).innerHTML = `${m}`
    document.querySelector(elementId[2]).innerHTML = `${seconds}`
    }else {
    document.querySelector(elementId).innerHTML = times;
    }
        // If the count down is finished, write some text
        if (distance < 0) {
            clearInterval(x);
        }
    }, 1000);
}


// time : string
// elementId : string / array(idhours, idminutes, idsecond)
window.countdowntimeOdl = function (servertime, time, elementId) {
  // Set the date we're counting down to
  var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  var date = new Date();
  date.setHours(servertime.split(':')[0], servertime.split(':')[1]); //set to servertime

  if(time == ':' || time == '00:') {
		date.setDate(date.getDate() + 1);
		date.setHours('00','00','01');
		time = '00:01';
	}

	var dateset = date.toLocaleDateString("en-US", options);
	var countDownDate = new Date(`${dateset} ${time}`);

	if (time.substring(0, 1) < date.getHours()) {
		countDownDate.setDate(countDownDate.getDate() + 1);
	}
	// Update the count down every 1 second
	var x = setInterval(function() {

		// Get todays date and time
		var now = new Date().setHours(servertime.split(':')[0], servertime.split(':')[1]);

		// Find the distance between now and the count down date
		var distance = countDownDate - now;
		// Time calculations for days, hours, minutes and seconds
		var days = Math.floor(distance / (1000 * 60 * 60 * 24));
		var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
		var seconds = Math.floor((distance % (1000 * 60)) / 1000);

		var h = (hours > 0) ? `${hours}` : 00;
		var m = (minutes > 0) ? `${minutes}` : 00;

    if ($.isArray(elementId)) {
      document.querySelector(elementId[0]).innerHTML = `${h}`
      document.querySelector(elementId[1]).innerHTML = `${m}`
      document.querySelector(elementId[2]).innerHTML = `${seconds}`
    }else {
      document.querySelector(elementId).innerHTML = `${h}:${m}:${seconds}`
    }

		// If the count down is finished, write some text
		if (distance < 0) {
			clearInterval(x);
		}
	}, 1000);
}
// color : string
//funtion for check color is dark or not
window.getBrightness = function (color) {
    // check if color in gradient
    var regex_gr = /gradient/gi; //for gradient
    var regex_rgb = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/i; //for rgb

    if(regex_gr.test(color)){
        // in gradient
        // Mencari semua nilai warna dalam gradien
        const rgbValues = color.match(/rgb\((\d+), (\d+), (\d+)\)/g);

        // Menghitung nilai kecerahan dari setiap titik gradien
        const brightnessValues = rgbValues.map(rgbValue => {
        const [r, g, b] = rgbValue.match(/\d+/g).map(Number);
            return Math.sqrt(
                0.299 * Math.pow(r, 2) +
                0.587 * Math.pow(g, 2) +
                0.114 * Math.pow(b, 2)
            );
        });
        var totalBrightness = 0;
        for (var i = 0; i < brightnessValues.length; i++) {
            totalBrightness += brightnessValues[i];
        }
        var brightness = totalBrightness / brightnessValues.length;

    }else if(regex_rgb.test(color)){
        // in RGB
        var match = color.match(regex_rgb);
        var red = parseInt(match[1]);
        var green = parseInt(match[2]);
        var blue = parseInt(match[3]);
        var brightness = Math.round(((red * 299) + (green * 587) + (blue * 114)) / 1000);
    }else{
        // in normal color
        // Mengambil nilai RGB dari warna
        var red = parseInt(color.substr(1, 2), 16);
        var green = parseInt(color.substr(3, 2), 16);
        var blue = parseInt(color.substr(5, 2), 16);

        // Menghitung nilai kecerahan warna
        var brightness = (red * 299 + green * 587 + blue * 114) / 1000;
    }       
        // Jika nilai kecerahan warna di bawah batas, maka warna dianggap gelap
        return brightness;
}
// color : string
//funtion for check color is dark or not
window.isColorDark = function (color) {
    var brightness = getBrightness(color);   
    // Jika nilai kecerahan warna di bawah batas, maka warna dianggap gelap
    return brightness < 128;
}

//maincolor, coloroption1, coloroption2 = String
// global funtion untuk menentukan color yg pas dengan inputan main color
window.findMatchingColor = function(mainColor, colorOption1, colorOption2, minimalbrightness = 50, maxbrightness = 210) {
    var brightness = getBrightness(mainColor);   
    // Jika nilai kecerahan warna di bawah batas, maka warna dianggap gelap
    return (brightness < minimalbrightness || brightness > maxbrightness) ? colorOption1 : colorOption2;
}

// check img exist by domain
// variable url : string (url img)
// return : url img
window.checkImgExist = function (url) {
    return new Promise(function(resolve, reject) {
        var img = new Image();
        img.onload = function() {
            resolve(url);
        };
        img.onerror = function() {
            reject(url);
        };
        img.src = url;
    });
}

window.randomStr = function (len){
    var arr = '12345abcde';
    let ans = '';
    for (let i = len; i > 0; i--) {
        ans +=
            arr[(Math.floor(Math.random() * arr.length))];
    }

    return ans;
}