// date function
function date_range_calculator(n) {
    firDay = days_left_in_range(n);
    firDay.setMonth(firDay.getMonth() - (n - 1));
    firDay.setDate(1);
    lasDay = days_left_in_range(n);

    return [firDay, lasDay]
}

function date_to_sting(d, type = 1) {
    var date = new Date(d);

    switch (type) {
        case 1:
            return moment(date).format('YYYY-MM-DD');
        case 2:
            return moment(date).format('YYYYMMDD');
        default:
            break;
    }
}

function get_now_time_stamp() {
    return Math.round(new Date().getTime() / 1000);
}

function days_left_in_range(n, d) {
    d = d || new Date();
    var qEnd = new Date(d);
    qEnd.setMonth(qEnd.getMonth() + n - qEnd.getMonth() % n, 0);
    return qEnd;
}

function last_date(_today) {
    day = new Date(_today.getFullYear(), _today.getMonth()+1,0);

    day = _today.getFullYear()+"-"+("0"+(day.getMonth()+1)).slice(-2)+"-"
        +("0"+(day.getDate())).slice(-2);
    return day;
}

function to_date(date_str) {
    var yyyyMMdd = String(date_str);
    var sYear = yyyyMMdd.substring(0,4);
    var sMonth = yyyyMMdd.substring(4,6);
    var sDate = yyyyMMdd.substring(6,8);

    return new Date(Number(sYear), Number(sMonth)-1, Number(sDate));
}

function date_range_vending_machine(date_range) {
    let firDay = '1990-01-01', lasDay = '3000-12-31';
        switch (date_range) {
            case 'day':
                firDay = new Date();
                lasDay = new Date();
                break;
            case 'week':
                firDay = moment(new Date()).startOf('isoWeek').format('YYYY-MM-DD');
                lasDay = moment(firDay).day(+7);
                break;
            case 'month':
                firDay = new Date();
                firDay.setDate(1);
                lasDay = last_date(new Date());
                break;
            case 'quarterly':
                [firDay, lasDay] = date_range_calculator(3)
                break;
            case 'semiannual':
                [firDay, lasDay] = date_range_calculator(6)
                break;
            case 'year':
                [firDay, lasDay] = date_range_calculator(12)
                break;
            default:
                break;
        }

        return [firDay, lasDay];
}
