const fs = require('fs');
const path = require('path');

const DIR_SOURCES = path.resolve('src');

const fileGetContents = filePath => fs.readFileSync(filePath, 'utf-8');

const ensureCopyright = (file, contents) => {
  if(
    contents.includes('Copyright (c)') &&
    contents.includes('MIT')
  ) return;
  throw new Error(`${file} is missing its copyright!`);
}

const ensurePragma = (file, contents) => {
  if(contents.includes('#pragma once')) return;
  throw new Error(`${file} is missing a #pragma once`);
}


const fileHandleCpp = filePath => {
  // Load contents
  const contents = fileGetContents(filePath);
  ensureCopyright(filePath, contents);
}

const fileHandleC = filePath => {
  // Load contents
  const contents = fileGetContents(filePath);
  ensureCopyright(filePath, contents);
}

const fileHandleHpp = filePath => {
  // Load contents
  const contents = fileGetContents(filePath);

  ensureCopyright(filePath, contents);
  ensurePragma(filePath, contents);
}

const fileHandleH = filePath => {
  // Load contents
  const contents = fileGetContents(filePath);

  ensureCopyright(filePath, contents);
  ensurePragma(filePath, contents);
}

const fileHandleCmake = filePath => {
  // Load contents
  const contents = fileGetContents(filePath);

  // Check for the copyright
  ensureCopyright(filePath, contents);
}



const fileScan = filePath => {
  const ext = path.extname(filePath).replace(/\./g, '');
  const base = path.basename(filePath);

  if(ext === 'cpp') {
    fileHandleCpp(filePath);
  } else if(ext === 'hpp') {
    fileHandleHpp(filePath);
  } else if(ext === 'c') {
    fileHandleC(filePath);
  } else if(ext === 'h') {
    fileHandleH(filePath);
  }else if(base === 'CMakeLists.txt') {
    fileHandleCmake(filePath);
  } else {
    throw new Error(`Unknown file type ${filePath}`);
  }
};

const dirScan = directory => {
  const contents = fs.readdirSync(directory);
  contents.forEach(filePath => {
    const abs = path.join(directory, filePath);
    const stat = fs.statSync(abs);
    if(stat.isDirectory()) {
      dirScan(abs);
    } else {
      fileScan(abs);
    }
  });
}

(() => {
  dirScan(DIR_SOURCES);
  console.log('Lint done');
})();