const { chromium, webkit } = require('playwright');
const $ = require('cheerio').default;
const jsonfile = require('jsonfile')
const url = 'https://klse.i3investor.com/web/stock/trending-now';
const fileName = 'klse_trend.json';

(async () => {
    try {

        console.log('Initialization');
        const browser = await chromium.launch();
        const page = await browser.newPage();
        await page.goto(url);
        console.log(`Fetching content of ${url}`);

        const html = await page.content();
        const data = getData(html);

        console.log('Writing data to file');

        writeToFile(data);

        await browser.close();

        console.log('Script executed successfully!');
    }
    catch (e) {
        console.log(e);
    }

})();


const writeToFile = (data) => {
    jsonfile.writeFileSync(fileName, data);
}


const getData = (html) => {
    const data = [];
    $('#dttable-stn-list tbody tr', html).each((index, element) => {
        const obj = {};
        $('td', element).each((index, element) => {
            switch (index) {
                case 1:
                    obj.rank = $(element).text();
                    break;
                case 2:
                    obj.stock_name = $(element).text();
                    obj.stock_url = 'https://klse.i3investor.com' + $(element.firstChild).attr('href');
                    break;
                case 3:
                    obj.company = $(element).text();
                    break;
                case 4:
                    obj.score = $(element).text();
                    break;
            }
        });
        data.push(obj);
    });
    return data;
}
