#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##

import os
import sys
import time
# import simplejson as json
# from threading import Timer


##################################################
# construct registration

import _rightThumb._construct as __
appDBA = __.clearFocus( __name__, __file__ )
# appDBA = __name__
__.appReg = appDBA
def focus( parentApp='', childApp='', reg=True ):
    global appDBA
    f = __.appName( appDBA, parentApp, childApp )
    if reg:
        __.appReg = f
    return f
__.registeredApps.append(focus())


import _rightThumb._base3 as _
_.load()

##################################################

import _rightThumb._vars as _v
import _rightThumb._string as _str
# import _rightThumb._profileVariables as _profile
#     profile = _profile.records.audit( 'name', asset )
# import _rightThumb._encryptString as _blowfish
    # _blowfish.genPassword()
    # _blowfish.genPassword('string')
    # en = _blowfish.encrypt( string )
    # de = _blowfish.decrypt( en )
# import _rightThumb._encryptFile as _blowfish
#     _blowfish.encrypt( infilepath, outfilepath, key )
#     _blowfish.decrypt( infilepath, outfilepath, key )
# _browser = _.regImp( __.appReg, '_rightThumb._toolsScrapeFrontEnd' )
# _browserX = _.regImp( __.appReg, '_rightThumb._toolsScrapeDirect' )
# import _rightThumb._date as _date
# import _rightThumb._dir as _dir
    # _.printVar( _dir.fileInfo( path ) )
# import _rightThumb._md5 as _md5
# import _rightThumb._mimetype as _mime

# import _rightThumb._backupLog as _bkLog
# _bkLog = _.regImp( __.appReg, '_rightThumb._backupLog' )

# import _rightThumb._auditCodeBase as _code
# _code = _.regImp( __.appReg, '_rightThumb._auditCodeBase' )
# _omit = _.regImp( __.appReg, 'omitTable' )
    # _omit.imp.inTable( 'the' )
# _inDic = _.regImp( __.appReg, 'inDic' )
    # _inDic.switch( 'All' )
    # _inDic.imp.testAll( 'fight' )
    # _inDic.imp.testOne( 'austen' )
# _file_folder = _.regImp( __.appReg, 'file_folder' )
#     _file_folder.switch( 'Save,Clean' )
#     _file_folder.switch( 'Compair,Clean' )
#     _file_folder.switch( 'Folder', '' )
# _fileNameDate = _.regImp( __.appReg, 'fileNameDate' )
#     _fileNameDate.imp.newName( filename )
#     _fileNameDate.imp.newName( filename, _dir.fileInfo( filename ) )
# _filePathPatterns = _.regImp( __.appReg, 'filePathPatterns' )
    # _filePathPatterns.switch( 'NoPrint' )
    # _filePathPatterns.switch( 'Files', _.switches.value('Files') )
    # folderReport = _filePathPatterns.action()
# txtBackup = _.regImp( __.appReg, 'txtBackup' )
#     txtBackup.switch( 'Input', filename )
#     txtBackup.switch( 'Flag', 'pre replaceText' )
#     recoveryFile = txtBackup.do( 'action' )
##################################################

# from lxml import html
# import requests
# import cssselect
# import sqlite3

##################################################


def appSwitches():
    pass
    _.switches.register( 'Race', '-r,-race' )
    _.switches.register( 'Files', '-f,-file,-files','file.txt', isPipe=True, description='List of character names' )
    # _.switches.register( 'Files', '-f,-file,-files','file.txt', isPipe='name,data,clean', description='' )


    """
    _.switches.documentation( 'Test', { 
                                        'examples': [
                                                        '',
                                                    ],

                                        'required': [],
                                        'related': [],
                                        'isRequired': False,
                                    } )
    """


_.autoBackupData = True
__.isRequired_Pipe = False
__.isRequired_Pipe_or_File = True
# __.isRequired_or_List = ['Pipe','Files','Plus']

_.appInfo[focus()] = {
    'file': 'DnD_name_tool.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'Tool to build DnD name tables',
    'categories': [
                        'dnd',
                        'name',
                ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        'p DnD_name_tool -race elf',
                        ''
    ],
    'columns': [
                       # { 'name': 'name', 'abbreviation': 'n' },
    ],
    'aliases': [
                       # 'this',
                       # 'app',
    ],

    }

_.appData[focus()] = {
    'start': __.startTime,
    'uuid': '',
    'audit': [],
    'pipe': False,
    'data': {
                'field': {'sent': [], 'received': [] }, # { 'label': '', 'context': [],  }
                'table': {'sent': [], 'received': [] }, 
    },
    }

# _.appInfo[focus()]['examples'].append('p thisApp -file file.txt')

# _.appInfo[focus()]['columns'].append({'name': 'name', 'abbreviation': 'n'})





def registerSwitches( argvProcessForce=False ):
    global appDBA
    if not __.appReg == appDBA and appDBA in __.appReg:

        if not __name__ == '__main__':
            _.argvProcess = argvProcessForce
        else:
            _.argvProcess = True

        _.load()
        _.appInfo[__.appReg] = _.appInfo[appDBA]
        _.appData[__.appReg] = _.appData[appDBA]
    __.constructRegistration(_.appInfo[__.appReg]['file'],__.appReg)
    appSwitches()

    _.myFileLocation_Print = False
    _.switches.trigger('Files',_.myFileLocations)
    # _.switches.trigger('Files',_.inRelevantFolder)
    

    # _.switches.trigger('Watched', _.txt2Date)
    # _.switches.trigger('Input',_.formatColumns)
    # _.switches.trigger('Franchise',_.triggerSpace)
    
    _.defaultScriptTriggers()
    _.switches.process()




if not __name__ == '__main__':
    _.argvProcess = False
else:
    _.argvProcess = True

registerSwitches()



def fieldSet( switchName, switchField, switchValue, theFocus=False ):
    if not type( theFocus ) == bool:
        theFocus = theFocus
    _.switches.fieldSet( switchName, switchField, switchValue, theFocus )


if __name__ == '__main__':
    if not sys.stdin.isatty():
        _.setPipeData( sys.stdin.readlines(), __.appReg )

_.postLoad( __file__ )

########################################################################################
# data = _.tables.returnSorted( 'data', 'd.timestamp', data )
# _.switches.fieldSet( 'Long', 'active', True )
# _.tables.register( 'data', table )
# _.tables.print( 'data', 'name' )
# p = _.getText( _v.pips, raw=True, clean=True ).split('\n')
# os.system('"' + do + '"')
# _.setPipeData( os.listdir(os.getcwd()), focus() )
# _.showLine(item)
#     if os.path.isdir(row):
#     if os.path.isfile(row):
# __.appRegPipe
########################################################################################
# START

def elf( row ):
    global data
    if ' – ' in row:
        name = row.split( ' – ' )
        if 'Male' in name[1]:
            data['male'].append({ 'name': name[0], 'sortID': '' })
        if 'Female' in name[1]:
            data['female'].append({ 'name': name[0], 'sortID': '' })


    # _.pr( 'elf', row )

def orc( i, row ):
    row = eval( row )
    # _.pr( 'i:', i, type(row), len(row), len(row[0]), row[0]  )
    # sys.exit()
    if i == 0:
        for ii,nameX in enumerate(row[0]):

            # _.pr( nameX )
            for name in (nameX.split('\n')):
            # _.pr( name )
            # if ii == 0:
            #     _.pr( name )
            #     sys.exit()
                if '. ' in name:
                    n = name.split('. ')[1]
                    # _.pr( n )
                    if i == 0:
                        data['male'].append({ 'name': n, 'sortID': '' })
                    else:
                        data['female'].append({ 'name': n, 'sortID': '' })
    else:
        # _.pr( 'i:', i, type(row), len(row), len(row[0]), row[0]  )
        # sys.exit()
        for name in (row[0].split('\n')):
        # _.pr( name )
        # if ii == 0:
        #     _.pr( name )
        #     sys.exit()
            if '. ' in name:
                n = name.split('. ')[1]
                # _.pr( n )
                if i == 0:
                    data['male'].append({ 'name': n, 'sortID': '' })
                else:
                    data['female'].append({ 'name': n, 'sortID': '' })


    # _.pr( row )
def tiefling( row ):
    global status

    if row == 'FEMALE' or row == 'SURNAMES':
        status+=1
        return False

    if status == 0:
        data['male'].append({ 'name': row, 'sortID': '' })
    if status == 1:
        data['female'].append({ 'name': row, 'sortID': '' })
    if status == 2:
        data['surname'].append({ 'name': row, 'sortID': '' })

def human( row ):
    global status

    if row == 'FEMALE' or row == 'SURNAMES':
        status+=1
        return False

    if status == 0:
        data['male'].append({ 'name': row, 'sortID': '' })
    if status == 1:
        data['female'].append({ 'name': row, 'sortID': '' })
    if status == 2:
        data['surname'].append({ 'name': row, 'sortID': '' })


def action():
    global data
    # load()

    if not type( _.appData[__.appReg]['pipe'] ) == bool:
        _.pipeCleaner()
        # _.printVar(_.appData)
        shouldRun = True
        if _.switches.isActive( 'Race' ) and ( _.switches.value( 'Race' ) == 'elf' or _.switches.value( 'Race' ) == 'orc' or _.switches.value( 'Race' ) == 'human' ):
            data = {}
            data['male'] = []
            data['female'] = []

        if 'tiefling' in _.switches.value( 'Race' ).lower() or _.switches.value( 'Race' ) == 'halfling' :
            data = {}
            data['male'] = []
            data['female'] = []
            data['surname'] = []

        if shouldRun:
            for i,row in enumerate(_.appData[__.appReg]['pipe']):
                if not _.switches.isActive( 'Race' ):
                    _.pr( row )
                else:
                    if 'elf' in _.switches.value( 'Race' ).lower():
                        elf( row )
                    if 'orc' in _.switches.value( 'Race' ).lower():
                        orc( i, row )
                    if 'tiefling' in _.switches.value( 'Race' ).lower():
                        tiefling( row )
                    if 'halfling' in _.switches.value( 'Race' ).lower():
                        tiefling( row )
                    if 'human' in _.switches.value( 'Race' ).lower():
                        human( row )

                        


        if _.switches.isActive( 'Race' ) and len( _.switches.value( 'Race' ) ):
            file = 'dndNames_' +_.switches.value( 'Race' ) + '.js'
            _.saveTable2( data, file )
            _.printBold( file, 'green' )



# def load():
#     global data
#     data = _.getData( 'table' )

status = 0
data = []
########################################################################################
if __name__ == '__main__':
    action()






