#!python
#
#   This is the Robotics Language compiler
#
#   Created on: June 22, 2017
#       Author: Gabriel A. D. Lopes
#      Licence: Apache 2.0
#    Copyright: 2014-2017 Robot Care Systems BV, The Hague, The Netherlands. All rights reserved.
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
import os
import re
import yaml
import shutil
import subprocess
import dpath.util
from RoboticsLanguage.Base import Utilities

language_path = os.path.dirname(__file__) + '/../../'
compiler_reference_path = language_path + 'Documentation/Compiler/Reference/'
language_reference_path = language_path + 'Documentation/Language/Reference/'
ignore = ['Scripts/tests', '__init__.py', 'Tools/tests.py', 'Manifesto.py', 'Parameters.py', 'Language.py']

# get all the modules to document
list_of_modules = filter(lambda x: x is not None, [file.replace(language_path, '').replace('.py', '') if all(
    [text not in file for text in ignore]) else None for file in Utilities.findFileType('py', language_path)])

# create generation list
generate = '\n'.join(['- ' + file + '/README.md:\n  - ' + file.replace('/', '.') + '+' for file in list_of_modules])

# create a tree to make the page structure
tree = {}
[dpath.util.new(tree, item, item + '/README.md') for item in list_of_modules]

# export in yaml format
pages_list = yaml.dump(tree, default_flow_style=False)

# append `-` to each line
pages = re.sub(r'(\s*)([a-zA-Z]*:.*)', r'\1- \2', pages_list)

# the template for the pyDocMd yaml file
template = '''
site_name: "The Robotics Language"

generate:
{}

pages:
- Home: index.md << README.md
{}

docs_dir: sources
gens_dir: _build/pydocmd     # This will end up as the MkDocs 'docs_dir'
site_dir: _build/site
theme:    readthedocs
loader:   pydocmd.loader.PythonLoader
preprocessor: pydocmd.preprocessor.Preprocessor

additional_search_paths:
- ../../..
'''

# save the pydocmd.yml file
with open(compiler_reference_path + 'pydocmd.yml', 'w') as pydoc:
  pydoc.write(template.format(generate, pages))

# create the index for the README.md file
index = re.sub(r'(\s*)([a-zA-Z]*):', r'\1- \2', re.sub(r'(\s*)([a-zA-Z]*):(.+)', r'\1- [\2](\3)', pages_list))

# the template for the README.md file
template = """
# Robotics Language compiler reference

{}
"""

# save the README.md file
with open(compiler_reference_path + 'README.md', 'w') as readme:
  readme.write(template.format(index))

# run the pydocmd script
process = subprocess.Popen(['pydocmd', 'build'], cwd=compiler_reference_path)
process.wait()

# move files
for filename in os.listdir(compiler_reference_path + '_build/pydocmd/'):
  shutil.move(compiler_reference_path + '_build/pydocmd/' + filename, compiler_reference_path + filename)

# clean up
shutil.rmtree(compiler_reference_path + '_build')
os.remove(compiler_reference_path + 'index.md')
os.remove(compiler_reference_path + 'pydocmd.yml')

# create RoL language Reference
process = subprocess.Popen(['rol', language_path+'Examples/helloworld.rol', '-o', 'Developer', '--create-reference-documentation', '-p', language_reference_path])
process.wait()
