const fs = require('fs');
let html = fs.readFileSync('site/tools/merchant-feed-generator.html', 'utf-8');

html = html.replace(/Google Merchant feed generator/g, 'Facebook product feed generator');
html = html.replace(/Free Google Merchant Feed Generator/g, 'Free Facebook Product Feed Generator');
html = html.replace(/merchant-feed-generator/g, 'facebook-product-feed-generator');
html = html.replace(/Google Merchant Center-ready XML feed/g, 'Facebook/Instagram Commerce Manager-ready CSV feed');
html = html.replace(/Google Merchant Center/g, 'Facebook Catalog');
html = html.replace(/Merchant feed XML/g, 'Facebook feed CSV');
html = html.replace(/merchant-feed\.xml/g, 'facebook-feed.csv');
html = html.replace(/application\/xml/g, 'text/csv');
html = html.replace(/\bxml\b/g, 'csv');
html = html.replace(/\bXML\b/g, 'CSV');

const csvBuildFeed = `  function buildFeed(items){
    var header = 'id,title,description,availability,condition,price,link,image_link,brand';
    var rows = items.map(function(p){
      var v = [p.id, p.title, p.description, p.availability || 'in_stock', p.condition || 'new', p.price, p.link, p.image_link, p.brand];
      return v.map(function(val){
        var str = String(val == null ? "" : val);
        if (/[",\\n]/.test(str)) return '"' + str.replace(/"/g, '""') + '"';
        return str;
      }).join(',');
    });
    $('output').textContent = [header].concat(rows).join('\\n');
    $('feed-output-section').classList.remove('hidden');
  }`;

html = html.replace(/  function buildFeed\(items\)\{[\s\S]*?  \}/, csvBuildFeed);

fs.writeFileSync('site/tools/facebook-product-feed-generator.html', html, 'utf-8');
console.log('Done');
