const date = require('date-and-time');
const fs = require('fs/promises');

function sort_array(array) {
    let arrleangth = array.length;
    let swapped = true;
    while (swapped === true) {
        let not_swapped = 0;
        for (let i = 0; i < arrleangth - 1; i++) {

            if (array[i] >= array[i + 1]) {
                swap(array, i, i + 1);
                not_swapped = 0;
            }
            else {
                not_swapped++;
            }
        }

        if (not_swapped >= arrleangth - 1) {
            swapped = false;
        }
    }
    return array
}

function swap(array, index1, index2) {
    let temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
}


function csl(...args) {
    console.log(...args);
}

function isEven(num) {
    if (num % 2 == 0) {
        return true;
    } else {
        return false;
    }
}

function isOdd(num) {
    if (num % 2 == 1) {
        return true;
    } else {
        return false;
    }
}

async function PostReq(url, data) {
    try {
        const res = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        if (!res.ok) throw new Error(`HTTP error ${res.status}`);
        const jsonResponse = await res.json();
        return jsonResponse; // Return the response in case you need it
    } catch (err) {
        console.error("POST error:", err);
        throw err; // Optional: Rethrow the error if you want to handle it elsewhere
    }
}


async function GetReq(url) {
    try {
        const res = await fetch(url);
        if (!res.ok) throw new Error(`HTTP error ${res.status}`);
        const data = await res.json();
        return data
    } catch (err) {
        console.error("Fetch error:", err);
        throw err;
    }
}


function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function readFromFile(filePath) {
    try {
        const content = await fs.readFile(filePath, 'utf8'); // Read file content
        return content; // Return the content as a string
    } catch (error) {
        console.error(`Error reading file at ${filePath}:`, error);
        throw error; // Rethrow the error for the caller to handle
    }
}

function writeToFile(file, data) {

    isWriting = true;
    fs.writeFile(file, JSON.stringify(data, null, 2), (err) => {
            isWriting = false;
        if (err) {
            return err;
        } else {
            return 'Task state updated successfully';
        }
    });
}

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getDateTime(input) {
    if (input) {
        if (input.toLowerCase() == 'time') {
            return date.format(new Date(), 'HH:mm:ss');
        }
        else if (input.toLowerCase() == 'date') {
            return date.format(new Date(), 'YYYY/MM/DD');
        }
        else if (input.toLowerCase() == 'day') {
            return date.format(new Date(), 'ddd');
        }
    }
    else {
        return "No input provided";
    }
}

global.sort_array = sort_array;
global.csl = csl;
global.isEven = isEven;
global.isOdd = isOdd;
global.PostReq = PostReq;
global.GetReq = GetReq;
global.sleep = sleep;
global.readFromFile = readFromFile;
global.writeToFile = writeToFile;
global.randomInt = randomInt;
global.getDateTime = getDateTime;
