var CWD=process.cwd();

var path=require('path');
var fs=require('fs');
var os=require('os');
var languages=require(CWD+'/languages.js');
var glob=require('glob');

function splitHeader(content){
var lines=content.split(os.EOL);
var i=1;
for(;i<lines.length-1;++i){
if(lines[i]==='---'){
break;
}
}
return{
header:lines.slice(1,i+1).join('\n'),
content:lines.slice(i+1).join('\n')};

}


function extractMetadata(content){
var metadata={};
var both=splitHeader(content);
var lines=both.header.split('\n');
for(var i=0;i<lines.length-1;++i){
var keyvalue=lines[i].split(':');
var key=keyvalue[0].trim();
var value=keyvalue.slice(1).join(':').trim();

try{
value=JSON.parse(value);
}catch(e){}
metadata[key]=value;
}
return{metadata:metadata,rawContent:both.content};
}

function processMetadata(file){
var result=extractMetadata(fs.readFileSync(file,'utf8'));

var language='en';

var metadata=result.metadata;
var rawContent=result.rawContent;
metadata.source=path.basename(file);

metadata.localized_id=metadata.id;
metadata.id=language+'-'+metadata.id;
if(metadata.previous){
metadata.previous_id=metadata.previous;
metadata.previous=language+'-'+metadata.previous;
}
if(metadata.next){
metadata.next_id=metadata.next;
metadata.next=language+'-'+metadata.next;
}
metadata.language=language;

return{metadata:metadata,rawContent:rawContent};
}

function generateAll(){

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

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

var metadatas=[];

console.log(enabledLanguages);

var files=glob.sync('./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 res=processMetadata(file);
var metadata=res.metadata;
metadatas.push(metadata);
}
});


fs.writeFileSync(
__dirname+'/../core/metadata.js',
'/**\n'+
' * @generated\n'+
' */\n'+
'module.exports = '+
JSON.stringify(metadatas,null,2)+
';');

}

module.exports.processMetadata=processMetadata;
module.exports.generateAll=generateAll;