const fs = require('fs');

const srcUrlRegex = /url\((\\?["'])?(?!data:)\S+(\\?["'])?\)/g;

export function normalizeCssPaths(params: {paths: string[], outDir: string}) {
  params.paths = params.paths ? params.paths : [];
  params.paths.forEach(path => normalizeCssPath(path, params.outDir));
}

function normalizeCssPath(path: string, outputDirectory: string) {
  console.log(`Start processing ${path}`);
  const css: string = fs.readFileSync(path, 'utf8');
  let counter = 0;

  const processedCss = css.replace(srcUrlRegex, (srcUrl: string) => {
    if (srcUrl.search(outputDirectory) != -1) return srcUrl;

    let fileName = getFileName(srcUrl);
    let processedUrl = `url('${outputDirectory}/${fileName}')`;
    counter++;
    console.log(`Replaced ${srcUrl} -> ${processedUrl}`);
    return processedUrl;
  });
  console.log(`Replaced ${counter} urls`);
  fs.writeFileSync(path, processedCss);
}

function getFileName(srcUrl: string): string {
  let url = srcUrl.substring(4, srcUrl.length - 1); // unbox 'url(...)'
  url = url.replace(/(\\?["'])/g, '');
  let urlPaths = url.split('/');
  return urlPaths[urlPaths.length - 1].split('?')[0];
}