#!/usr/bin/python

import glob
import os
import subprocess


# In stella we don't really use the old way to translate rtf,
# so here is the swtich to decide you want to use old/new way to translate the rtf
# new:
#   - translate directly from trf to html via unrtf.
# old:
#   - need to decide langmap first.
#   - need specific naming rule for rtf name.
#   - have some customization for html

NEW_METHOD=True

#Autoconverts what it can
LANGMAP = \
{
'ja' : '',
'ru' : '',
'po' : '',
'bg' : '',
'lt' : '',
'sk' : '',
'th' : '',
'ar' : '',
'cs' : '',
'ct' : '',
'gk' : '',
'he' : '',
'ko' : '',
}

def convert():
    print("Converting RTF's to HTML")
    if NEW_METHOD:
        convert_new()
    else:
        convert_old()

def convert_new():
    for filepath in glob.glob("rtf/*.rtf"):
        filename = filepath.split('.')[0].split('/')[1]
        with open('html/%s.html' % filename, 'w') as fd:
            call = subprocess.Popen(['unrtf', filepath], stdout=fd , stderr=subprocess.PIPE)
            (out,err) = call.communicate()

def convert_old():
    EULAS = {}
    for filepath in glob.glob("rtf/*.rtf"):
        basename = os.path.basename(filepath)
        if 'OEM_Eula' in basename:
            split_name = filepath.split('.')[0].split('_')
            if len(split_name) > 2:
                lang = split_name[2].lower()
            else:
                lang = 'en'
            if LANGMAP.has_key(lang):
                if LANGMAP[lang]:
                    print("INFO: Mapping %s from Windows EULA to %s on Linux" % (lang, LANGMAP[lang]))
                    lang = LANGMAP[lang]
                else:
                    print("WARNING: Skiping %s.  It needs to be hand converted on Linux." % lang)
                    continue
            else:
                print("INFO: Autoconverting %s" % lang)
            EULAS[lang] = filepath
    if EULAS:
        for lang in EULAS:
            call = subprocess.Popen(['unrtf', EULAS[lang]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            original = os.path.basename(EULAS[lang]).split('.')[0]
            with open('html/%s.html' % original, 'w') as fd:
                (out,err) = call.communicate()
                for line in out.split('\n'):
                    if '(' in line and ')' in line:
                        left = line.index('(')
                        right = line.index(')')
                        sub = ''
                        for i in range(left,right+1):
                            sub+=line[i]
                        line = line.replace(sub,'<B>(OEM EULA)</B>')
                    fd.write(line + '\n')

if __name__ == '__main__':
    convert()
