import * as dns from "dns";
import * as fs from "fs";
import * as https from 'https';
import path from "path";

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

    }

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

    static downloadImage(url, filepath) {

        return new Promise((resolve, reject) => {
            try {
                if (!fs.existsSync(path.dirname(filepath)))
                    fs.mkdirSync(path.dirname(filepath));
            } catch (e) {

            }
            https.get(url, (res) => {
                if (res.statusCode === 200) {
                    res.pipe(fs.createWriteStream(filepath))
                        .on('error', reject)
                        .once('close', () => resolve(filepath));
                } else {
                    // Consume response data to free up memory
                    res.resume();
                    reject(new Error(`Request Failed With a Status Code: ${res.statusCode}`));

                }
            });
        });
    }

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

        }

    }

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

}