const fs = require('fs');
const util = require('util');
const stream = require('stream');
const pipeline = util.promisify(stream.pipeline);''

const axios = require('axios');
const html_parser = require('node-html-parser');


async function get_image_size(url) {
    try {
        const image = await axios.get(url);
        return image.headers['content-length'];
    } catch (error) {
        console.error(error);
        return error;
    }
}

async function save_image(url, path) {
    /* try {
        const image = await axios.get(url, {
            responseType: "stream"
        });

        image.data.pipe(fs.createWriteStream(path));

        const image_size = image.headers['content-length'];
        return image_size;
    } catch (error) {
        console.error(error);
        return error;
    } */

    try {
        const image = await axios.get(url, {
            responseType: "stream"
        });

        await pipeline(image.data, fs.createWriteStream(path));
        console.log("Image downloaded successfully");
    } catch (error) {
        console.error("Imae download failed: ", error);
        return error;
    }
}

async function get_radar_caption() {
    const response = await axios.get('https://weather.bangkok.go.th/Radar/RadarHighResolution.aspx');

    let root = html_parser.parse(response.data);
    console.log("Got Radar Caption")
    return root.querySelector('#repeaDaily_lblDESCRIPTION_0').childNodes[0]._rawText;
}

module.exports.get_image_size = get_image_size;
module.exports.save_image = save_image;
module.exports.get_radar_caption = get_radar_caption;