import * as dns from "dns";
import * as fs from "fs";
import * as https from 'https';
import path from "path";
import {Settings} from "./Settings";
import sharp from "sharp";

export class Utils {
    public static checkInternet(): Promise<boolean> {
        return new Promise(resolve => {
            dns.resolve('itender.gaminggeneration.de', (err, addresses) => {
                if (err)
                    resolve(false);
                else
                    resolve(true);
            });
        });

    }

    static sleep(ms: number): Promise<void> {
        return new Promise(resolve => {
            setTimeout(() => resolve(), ms);
        })
    }

    static downloadImage(url, id) {
        return new Promise((resolve, reject) => {
            // "./public/images/" + drink._id + ".png"
            let tempPath = path.join(process.cwd(), "./public/images/", id + "_pre.png");
            let finalPath = path.join(process.cwd(), "./public/images/", id + ".png");
            try {
                if (!fs.existsSync(path.dirname(tempPath)))
                    fs.mkdirSync(path.dirname(finalPath));
            } catch (e) {

            }
            https.get(url, (res) => {
                if (res.statusCode === 200) {
                    res.pipe(fs.createWriteStream(tempPath))
                        .on('error', reject)
                        .once('close', async () => {
                            try {
                                await sharp(tempPath).resize( { width: 400 } ).sharpen().toFile(finalPath);
                                fs.unlinkSync(tempPath);
                                resolve(finalPath);
                            } catch(e)
                            {
                                reject(e);
                            }
                        });
                } else {
                    // Consume response data to free up memory
                    res.resume();
                    reject(new Error(`Request Failed With a Status Code: ${res.statusCode}`));

                }
            }).on("error", (e) => {
                reject(new Error("Request failed " + e))
            });
        });
    }

    static deleteImage(id) {
        try {
            fs.unlinkSync("./public/images/" + id + ".png");
        } catch (e) {

        }

    }

    static checkForImage(id) {
        return fs.existsSync("./public/images/" + id + ".png");
    }

    static waitForReady(timeout: number = 0): Promise<void> {
        let millis = 0;
        return new Promise((resolve, reject) => {
            function wait() {
                millis += 100;
                if (Settings.setupDone) {
                    resolve()
                    return;
                }
                if (timeout != 0 && timeout <= millis) {
                    reject();
                    return;
                }

                setTimeout(() => wait(), 100);
            }

            setTimeout(wait, 100);
        });


    }

    static generateRandomString(len: number) {
        let result = '';
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        const charactersLength = characters.length;
        for (let i = 0; i < len; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
}