#!/usr/bin/env python3

"""
This script will convert TrueRewardsTOU.txt (Terms of Use) and TRUPrivacyPolicy.txt,
which are Google Docs saved to text format, into React components:

    src/components/PrivacyPolicyDoc.js
    src/components/TermsOfUseDoc.js

In case TOU or PP texts change, save the Google Docs to
TrueRewardsTOU.txt and/or TRUPrivacyPolicy.txt in text format,
rerun this script and commit git changes.
"""

import sys
from functools import reduce

def txt_file_to_html(file_name):
    with open(file_name, encoding='utf-8-sig') as f:
        return txt_to_html(f.readlines())


CENTERED="""TRU Purchaser Portal,Terms of Use,TRU Privacy Policy,Purchaser Portal""".split(',')

PP_DISCLAIMER="""While using TRU Purchase Portal you agree that you are familiar <br/> with Privacy Policy of our service and accept it. """
TOU_DISCLAIMER="""While using TRU Purchase Portal you agree that you are familiar <br/> with Terms of Use of our service and accept it."""

H3 = """Theft and Loss,Market Value,Liquidation Risk""".split(',')

# Last modified:
DATE="June 5, 2020"


REPLACEMENTS = [
    ('\xef\xbb\xbf', ''),  # UTF-8 byte order mark (BOM)
    ('\xe2\x80\x99', "&#x02019;"), # quote
    ("\xe2\x80\x9c",'&ldquo;'),
    ("\xe2\x80\x9d", '&rdquo;'),
    ("\xe2\x80\x94", "&mdash;"),
    ("www.ADD WEBSITE URL.com", '<a href="https://portal.trusttoken.com">portal.trusttoken.com</a>'),
    ("legal@trusttoken.com", '<a href="mailto:legal@trusttoken.com">legal@trusttoken.com</a>'),
    ("Terms of Use[a]", '<Link to="/terms-of-use"> Terms of Use </Link>'),
    ("[a]Add link.", ""),
]


def clean(line):
    return reduce(lambda s, r: s.replace(*r), REPLACEMENTS, line).strip()


def is_heading(line):
    """ Normally a heading is written without the line ending period.
        We have some with question marks.
    """
    return not (line[-1] in '.:/') or line.endswith("U.S.")


def heading(line):
    if '[DATE]' in line:
        return ''

    if line == "Purchaser Portal":
        return f'<h1 style={{{{textAlign: "center"}}}}>{line}</h1>' +\
               f'<p style={{{{textAlign: "center"}}}}>{PP_DISCLAIMER}</p>' +\
               f'<p style={{{{textAlign: "center"}}}}> Last modified: {DATE}</p>'

    if line == "Terms of Use":
        return f'<h1 style={{{{textAlign: "center"}}}}>{line}</h1>' +\
               f'<p style={{{{textAlign: "center"}}}}>{TOU_DISCLAIMER}</p>' +\
               f'<p style={{{{textAlign: "center"}}}}> Last modified: {DATE}</p>'

    if line in CENTERED:
        return f'<h1 style={{{{textAlign: "center"}}}}>{line}</h1>'
    if line in H3:
        return f"<h3>{line}</h3>"
    return f"<h2>{line}</h2>"


def txt_to_html(lines):
    in_ul = False
    for line in map(clean, lines):
        if not line or "[a]Add link." in line:
            continue
        if line.startswith('*'):
            if not in_ul:
                yield "<ul>"
                in_ul = True
            yield f"<li>{line[2:]}</li>"
        else:
            if in_ul:
                yield "</ul>"
                in_ul = False
            if is_heading(line):
                yield(heading(line))
            else:
                yield(f"<p>{line}</p>")


def convert(component_name, text_file, output_file):
    """
    Convert legal text file to React component (JSX).
    """
    document = '\n'.join(txt_file_to_html(text_file))

    if "Terms" in component_name:
        document = document.replace("Privacy Policy", '<Link to="/privacy-policy"> Privacy Policy </Link>', 1)

    react_component = f""" // This file is autogenerated. Do not edit! See {sys.argv[0]}
import React from 'react';
import {{ Link }} from 'react-router-dom';

const {component_name} = props => (
<>
{document}
</>
)
export default {component_name};
"""
    with open(output_file, "w") as f:
        f.write(react_component)


convert("PrivacyPolicyDoc", "TRUPrivacyPolicy.txt", "src/components/PrivacyPolicyDoc.js")
convert("TermsOfUseDoc", "TrueRewardsTOU.txt", "src/components/TermsOfUseDoc.js") 

