#!/usr/bin/env node
var _jsxFileName='website/server/generate.js';

var CWD=process.cwd();

var fs=require('fs-extra');
var readMetadata=require('./readMetadata.js');
var renderToStaticMarkup=require('react-dom/server').renderToStaticMarkup;
var path=require('path');
var toSlug=require('../core/toSlug.js');
var React=require('react');
var siteConfig=require(CWD+'/siteConfig.js');
var mkdirp=require('mkdirp');
var glob=require('glob');
var languages=require(CWD+'/languages.js');

console.log('generate.js triggered...');

function writeFileAndCreateFolder(file,content){
mkdirp.sync(file.replace(new RegExp('/[^/]*$'),''));

fs.writeFileSync(file,content);
}

var TABLE_OF_CONTENTS_TOKEN='<AUTOGENERATED_TABLE_OF_CONTENTS>';

var insertTableOfContents=function insertTableOfContents(rawContent){
var regexp=/\n###\s+(`.*`.*)\n/g;
var match=void 0;
var headers=[];
while(match=regexp.exec(rawContent)){
headers.push(match[1]);
}

var tableOfContents=headers.
map(function(header){return'  - ['+header+'](#'+toSlug(header)+')';}).
join('\n');

return rawContent.replace(TABLE_OF_CONTENTS_TOKEN,tableOfContents);
};

var regexSubFolder=/docs\/(.*)\/.*/;

var enabledLanguages=[];
languages.filter(function(lang){return lang.enabled;}).map(function(lang){
enabledLanguages.push(lang.tag);
});

readMetadata.generateAll();

var readCategories=require('./readCategories.js');
readCategories('docs');

var DocsPost=require('../core/DocsPost.js');

fs.removeSync(CWD+'/build');


var files=glob.sync(CWD+'/docs/**');
files.forEach(function(file){

var language='en';
var match=regexSubFolder.exec(file);
if(match){
language=match[1];
}

if(enabledLanguages.indexOf(language)===-1){
return;
}

var extension=path.extname(file);

if(extension==='.md'||extension==='.markdown'){
var result=readMetadata.processMetadata(file);

var metadata=result.metadata;
var rawContent=result.rawContent;

if(rawContent&&rawContent.indexOf(TABLE_OF_CONTENTS_TOKEN)!=-1){
rawContent=insertTableOfContents(rawContent);
}

var docComp=React.createElement(DocsPost,{config:siteConfig,metadata:metadata,language:language,content:rawContent,__source:{fileName:_jsxFileName,lineNumber:83}});
var str=renderToStaticMarkup(docComp);

writeFileAndCreateFolder(CWD+'/build'+siteConfig.baseUrl+metadata.permalink,str);
}
});

files=glob.sync(__dirname+'/../src/**');
files.forEach(function(file){
console.log(file);
var targetFile=file.replace('/lib/src/','/build'+siteConfig.baseUrl);
if(file.match(/\.js$/)){
targetFile=targetFile.replace(/\.js$/,'.html');
var ReactComp=require(file.replace('./lib/','../'));
var str=renderToStaticMarkup(React.createElement(ReactComp,{__source:{fileName:_jsxFileName,lineNumber:97}}));
writeFileAndCreateFolder(targetFile,str);
}else
if(!fs.lstatSync(file).isDirectory()){

mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'),''));
fs.copySync(file,targetFile);
}
});