const express = require("express");
const fetch = require("node-fetch");
const jsdom = require("jsdom");
const cron = require('node-cron');
const { JSDOM } = jsdom;

const melon = {
  data: {
    url: 'https://www.melon.com',
  },
  methods: {
    ccm: function () {
      const fetchingData = async () => {
        const res = await fetch(melon.data.url + '/genre/song_list.htm?gnrCode=GN2100')
          .then(res => res.text())
          .then(body => {
            data = [];
            const dom = new JSDOM(body);
            var table = dom.window.document.querySelector('.service_list_song table tbody').getElementsByTagName('tr');
            for(var i=0;i<table.length;i++) {
              var d = {}
              var tr = table.item(i);                            
              d.img = tr.querySelector('img').getAttribute('src');
              d.url = 'https://www.melon.com/album/detail.htm?albumId='+tr.querySelector(".wrap a").getAttribute('href').match(/\d+/)[0];
              d.title = tr.querySelector('.wrap_song_info a').textContent;
              d.album = tr.querySelector('.wrap_song_info .rank02 a').textContent;
              data.push(d);
            }
            
            melon.data.ccm = data;
          });
      };
      fetchingData();
    }
  }
}

cron.schedule('0 * * * *', () => {
  melon.methods.ccm();
  console.log('Fetching Melon CCM List Successfully');
});  

var app = express();
app.listen(20001, () => {  
  melon.methods.ccm();
  console.log("Server running on port 20001");
});


app.get('/melon/ccm', (req, res, next) => {
  res.json(melon.data.ccm)
})

