#!/usr/bin/python3
# -*- coding: utf-8 -*-

#  Copyright © 2012-2013  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.



import sys, os
sys.path.insert(0, '.')
import re

from pybiklib import config
from pybiklib.config import wrap

try:
    _
except NameError:
    import builtins
    builtins.__dict__['_'] = lambda s: s


def underline(title, underline_char='='):
    return '{}\n{}'.format(title, underline_char*len(title))

def clean_links(text):
    footnotes = []
    def add_footnote(match):
        if match.group(2) != '|':
            return match.group(0)
        elif match.group(1) != '':
            footnote = match.group(1)
            if footnote in footnotes:
                footnotes.append(footnotes.index(footnote)+1)
            else:
                footnotes.append(footnote)
            return ''
        else:
            footnote = footnotes[-1]
            if type(footnote) is int:
                del footnotes[-1]
                return ' [{}]'.format(footnote)
            else:
                return ' [{}]'.format(len(footnotes))
    text = re.sub(r'<(.*?)(\|?)>', add_footnote, text)
    return text, ['[{}] <{}>'.format(i+1, footnote) for i, footnote in enumerate(footnotes)]
    
def read_utf8(filename):
    with open(filename, 'rt', encoding='utf-8') as f:
        return f.read()
    
def write_utf8(filename, text):
    with open(filename, 'wt', encoding='utf-8') as f:
        f.write(text)
        
def create_README(filename=None, skip_install=False):
    if not filename:
        filename = 'README'
    news_template = [
            ('{appname}',   '{description}\n\n'
                            'Author: {AUTHOR} <{CONTACT_EMAIL}>\n'
                            'License: {LICENSE_NAME}\n'
                            'Project page: <{WEBSITE}>'),
            ('Installation', wrap(
                            'If Pybik is available for your distribution, '
                            'you should install Pybik with a package manager. '
                            'Otherwise see the file INSTALL for installation instructions.')),
            ('Feedback',    '{feedback}'),
            ('Translation', '{translation}'),
            ('License', '{license}'),
        ]
    readme = {
            'appname':      'About {} {}'.format(config.APPNAME, config.VERSION),
            'description':  wrap(config.LONG_DESCRIPTION),
            'AUTHOR':       config.AUTHOR,
            'CONTACT_EMAIL':config.CONTACT_EMAIL,
            'LICENSE_NAME': config.LICENSE_NAME,
            'WEBSITE':      config.WEBSITE,
            'feedback':     wrap(clean_links(config.get_filebug_text())),
            'translation':  wrap(clean_links(config.TRANSLATION_TEXT)),
            'license':      wrap(config.LICENSE_INFO) + '\n\n' + wrap(config.LICENSE_NOT_FOUND),
        }
        
    text = ''
    for title, body in news_template:
        if skip_install and title == 'Installation':
            continue
        title = underline(title.format(**readme))
        body = body.format(**readme)
        text += '\n{}\n\n{}\n\n'.format(title, body)
    write_utf8(filename, text)
    
    
def main():
    skip_install = False
    args = sys.argv[1:]
    if not args:
        print('usage: {} [--skip-install] README[=filename]'.format(os.path.basename(sys.argv[0])))
        sys.exit(1)
    for arg in args:
        if arg == '--skip-install':
            skip_install = True
        elif not arg.startswith('--'):
            fileinfo = arg.split('=', 1)
            if len(fileinfo) == 1:
                fileinfo.append(None)
            if fileinfo[0] == 'README':
                create_README(fileinfo[1], skip_install=skip_install)
            else:
                print('Unknown Argument:', arg)
                sys.exit(1)
        else:
            print('Unknown Option:', arg)
            sys.exit(1)
            
    
if __name__ == '__main__':
    try:
        _
    except NameError:
        __builtins__._ = lambda text: text
    main()
    

