# -*- coding: utf-8 -*-
import re
import sys
import os
import re
import subprocess
import urllib.parse
import urllib.request
import argparse
import string
import time
import configparser
import shutil
from tkinter import *


class Config():
    def __init__( self, root2cfgfile, **kwargs ):
        self.__configParser( root2cfgfile )
        self.__argParser()
        self.__unifying()

    def __configParser( self, root2cfgfile ):
        assert os.path.isfile( root2cfgfile ), 'Nincs config_vr.ini file ezen a path-on: "{}"'.format( os.path.abspath( root2cfgfile ) )
        self._cfg = configparser.ConfigParser()
        self._cfg.read( root2cfgfile )

    def __argParser( self ):
        usage = 'PROG [-lang LANGFOLDER]'
        description = 'Voice Recognition Content Generator tool.'
        self._argpars = argparse.ArgumentParser( description = description, usage = usage )
        help = 'A generáláshoz 1 nyelvkódot kell megadni ami egy SVN-ben létező langfolder neve kell legyen. Vagy, ha nincs megadva nyelvkód, akkor minden nyelv le lesz generálva.'
        self._argpars.add_argument( "-lang", default = 'all', help = help )

    def __unifying( self ):
        if self._argpars.parse_args().__dict__['lang'] == 'all':
            self.languages = self.__find_langFolders( 'source\\' )

            noSection = [l for l in self.languages if l not in self._cfg.sections() and l not in ( 'igo', 'engine', 'path', 'temp', 'source' )]
            noFolder = [l for l in self._cfg.sections() if l not in self.languages and l not in ( 'igo', 'engine', 'path', 'temp', 'source' )]
            assert not noSection, 'Van olyan langfolder "{}" amihez nincs a config_vr.ini-ben section!'.format( noSection )
            assert not noFolder, 'Van olyan lang section "{}" amihez nincs langfolder!'.format( noFolder )
        else:
            lang = self._argpars.parse_args().__dict__['lang']
            assert lang  in self._cfg.sections(), 'A megadott langhoz "{}" nincs section a config_vr.ini-ben!'.format( lang )
            self.languages = [lang]

    def __find_langFolders( self, path ):
        dirNames = [i for i in os.listdir( path ) if os.path.isdir( os.path.join( path, i ) ) and not i == '.svn']

        return dirNames

    def get_igo_branch( self ):
        return self._cfg["igo"]["igo_branch"]

    def get_igo_ui( self ):
        return self._cfg["igo"]["igo_ui"]

    def get_content_type( self ):
        return self._cfg["igo"]["content_type"]

    def get_asr_type( self ):
        return self._cfg["igo"]["asr_type"]

    def get_engineOutputFile_ver( self ):
        return self._cfg["igo"]["engineOutputFile_ver"]

    def get_provider( self ):
        return self._cfg["engine"]["provider"]

    def get_engine( self ):
        return self._cfg["engine"]["engine"]

    def get_engine_ver( self ):
        return self._cfg["engine"]["engine_ver"]

    def get_model_size( self ):
        return self._cfg["engine"]["model_size"]

    def get_model_freq( self ):
        return self._cfg["engine"]["model_freq"]

    def get_search_tree_type( self ):
        return self._cfg["engine"]["search_tree_type"]

    def get_content_generator( self ):
        return self._cfg["path"]["content_generator"]

    def get_vocon3200_install( self ):
        return self._cfg["path"]["vocon3200_install"]

    def get_output_folder( self ):
        return self._cfg["path"]["output_folder"]

    def get_python2vocon( self ):
        return self._cfg["path"]["python2vocon"]

    def get_7zip( self ):
        return self._cfg["path"]["7zip"]

    def get_languages( self ):
        return self.languages

    def get_lang_model_lang( self, lang ):
        return self._cfg[lang]['model_lang']

    def get_lang_model_lcid( self, lang ):
        return self._cfg[lang]['model_lcid']

    def get_lang_model_vers( self, lang ):
        return self._cfg[lang]['model_vers']

    def get_lang_house_number_first( self, lang ):
        return self._cfg[lang]['house_number_first']


class VRContentGenerator():
    def __init__( self, root ):
        self.root = root
        self.root.title( 'VR Content Generator' )

        self.sourceFolderPath = os.path.abspath( 'source' )
        self.tempFolderPath = os.path.abspath( '_temp' )
        self.outputFolderPath = os.path.abspath( '_out' )
        self.full_outputFolderPath = False
        self.timeStamp = time.strftime( '%Y_%m_%d__%H_%M_%S' )
        self.errorState = False

        self.config = Config( os.path.abspath( "source\\config_vr.ini" ) )

        self.mainContentType = 'vr'
        self.contentType = '{}_{}'.format( self.mainContentType, self.config.get_content_type().lower() )

        self.bnf_fileParser = BNFFileParser()

        self.__create_ui()

    def __create_ui( self ):
        left = Label( self.root, text = "select with\nDRAGGING or CTRL/SHIFT + CLICK" )
        left.pack()

        self.mainframe = Frame( self.root )
        self.mainframe.pack( side = TOP )

        self.bottomframe = Frame( self.root )
        self.bottomframe.pack( side = BOTTOM )

        self.__makeListBox()
        self.__makeButton()

    def __makeListBox( self ):
        list = Listbox( self.mainframe, relief = SUNKEN, selectmode = EXTENDED )
        sbar = Scrollbar( self.mainframe )
        list.config( yscrollcommand = sbar.set )
        sbar.config( command = list.yview )
        list.pack( side = LEFT, expand = YES, fill = BOTH )
        sbar.pack( side = RIGHT, fill = Y )

        pos = 0
        for i in sorted( self.config.get_languages() ):
            list.insert( pos, i )
            pos = pos + 1

        self.listbox = list

    def __makeButton( self ):
        genB = Button( self.bottomframe, text = 'generate selected', command = self.__generate_some )
        genB.pack( side = BOTTOM )

        selB = Button( self.bottomframe, text = 'generate ALL', command = self.__generate_all )
        selB.pack( side = TOP )

    def __generate_some( self ):
        index = self.listbox.curselection()
        selections = []
        for i in index:
            selections.append( self.listbox.get( i ) )

        self.main( selections )

    def __generate_all( self ):
        allItem = self.listbox.get( 0, END )
        self.main( allItem )

    def main( self, selection ):
        self.__create_tempFolder()
        # working with lang(s):
        for configLang in selection:
            lang = self.config.get_lang_model_lang( configLang )

            self.__creat_tempLangFolder( lang )

            print( '\nworking with "{}"...'.format( lang ) )

            # commands.bnf -> commands.lcf:
            inputFile = self.__generate_commands_lcf( lang )
            # commands.bnf -> commands.csv:
            outputFile = os.path.join( self.tempFolderPath, self.config.get_lang_model_lang( lang ), 'commands.csv' )
            self.bnf_fileParser.main( inputFile, outputFile )
            # house_number.bnf -> house_number.lcf:
            self.__generate_house_number_lcf( lang )
            # content.nng:
            vrPackName = self.__set_vnb_fileName( lang )
            cid = VRContentID( **{"Provider": self.config.get_provider(),
                                  "VREngine": self.config.get_engine(),
                                  "VREngineVer": self.config.get_engine_ver(),
                                  "VRContentType": self.config.get_content_type(),
                                  "iGOBranch": self.config.get_igo_branch(),
                                  "iGOUI": self.config.get_igo_ui(),
                                  "LangCode": lang,
                                  "VRFileName": vrPackName,
                                  "DestPath": os.path.join( self.tempFolderPath, self.config.get_lang_model_lang( lang ), ),
                                  "contentGenerator": self.config.get_content_generator(),
                                  } )
            if not cid.create():
                self.__remove_generation()
            # info.ini
            self.__create_info_ini( lang )
            # create a dest folder:
            self.__creat_outputFolderPath( lang, vrPackName )
            self.__creat_outputFolder()
            # create path to the zipping:
            path2zip = self.__create_path2zip( lang )
            # create a zip:
            self.__zip( lang, path2zip )
            # copy a zip into the _temp for developping:
            self.__copy_zip2Temp( path2zip )

            print( '\ndone.' )

    def __create_tempFolder( self ):
        try:
            os.makedirs( self.tempFolderPath, exist_ok = True )
        except:
            raise AssertionError( 'Nem sikerült létrehozni a "temp" foldert a további generáláshoz: "{}"'.format( self.tempFolderPath ) )

    def __creat_tempLangFolder( self, lang ):
        try:
            os.makedirs( os.path.join( self.tempFolderPath, lang ), exist_ok = True )
        except:
            raise AssertionError( 'Nem sikerült létrehozni a "temp" alatti "lang" foldert a további generáláshoz: "{}"'.format( self.tempFolderPath ) )

    def __creat_outputFolderPath( self, lang, vrPackName ):
        """
        _Output\TTS_Nuance\Demo\v5\2011_06_09__17_15_48\TTS_nua_eng_au_f1_lua-dri40-155mrf22\content\voice\
        _out\{Provider}\{Brand}\{Version}\{TimeStamp}\{CsomagNév}\content\vr\
        Provider = Nunace
        Brand = iGO_GM3
        Version = vocon_v3_4F1 # engine = vocon + _ + engine_ver = v3_4F1
        TimeStamp = 2011_06_09__17_15_48
        CsomagNév = vrPackName # %MODELLCID%_vocon34f1_%MODELLANG%.vnb
        """
        self.full_outputFolderPath = os.path.join( self.outputFolderPath,
                                                   self.contentType,
                                                   self.config.get_provider(),
                                                   self.config.get_igo_branch(),
                                                   '{}_{}'.format( self.config.get_engine(), self.config.get_engine_ver() ),
                                                   self.timeStamp,
                                                   lang,
                                                   'content',
                                                   'vr',
                                                   )

    def __creat_outputFolder( self ):
        try:
            os.makedirs( self.full_outputFolderPath, exist_ok = True )
        except:
            raise AssertionError( 'Nem sikerült létrehozni az "_out" foldert a további generáláshoz: "{}"'.format( self.outputFolderPath ) )

    def __set_vnb_fileName( self, lang ):
        # %MODELLCID%_vocon34f1_%MODELLANG%.vnb,
        fileName = '{}_{}_{}.vnb'.format( self.config.get_lang_model_lcid( lang ),
                                          self.config.get_engineOutputFile_ver(),
                                          self.config.get_lang_model_lang( lang ),
                                           )

        return fileName

    def __generate_commands_lcf( self, lang ):
        """
        @set INPUT=%MODELLANG%\commands.bnf
        @set OUTPUT=temp/%MODELLANG%/commands.lcf
        %PYTHON_TL% "%VOCON3200_INSTALL_PATH%\tools\contextcpl.pyc" -p contextcpl.param --grammarFilepaths=%INPUT% --contextBufferFilepath=%OUTPUT% --modelFilepath=..\..\..\..\vocon\models\acmod3_%MODELSIZE%_%MODELLANG%_gen_car_f%MODELFREQ%_%MODELVERS%.dat --contextBufferSearchTreeType=%SEARCHTREETYPE% --useg2p=true --useComputedParameters=true
        """
        print( '\n\tcreating the "commands.lcf" file...' )

        inputFile = os.path.abspath( os.path.join( self.sourceFolderPath, self.config.get_lang_model_lang( lang ), 'commands.bnf' ) )
        outputFile = os.path.join( self.tempFolderPath, self.config.get_lang_model_lang( lang ), 'commands.lcf' )

        return self.__generate_lcf( lang, inputFile, outputFile )

    def __generate_lcf( self, lang, inputFile, outputFile ):
        arguments = [self.config.get_python2vocon(), # %PYTHON_TL%
                     os.path.join( self.config.get_vocon3200_install(), 'tools', 'contextcpl.pyc' ), # "%VOCON3200_INSTALL_PATH%\tools\contextcpl.pyc"
                     '-p',
                     'source\\contextcpl.param', # -p contextcpl.param
                     '--grammarFilepaths={}'.format( inputFile ), # --grammarFilepaths=%INPUT%
                     '--contextBufferFilepath={}'.format( outputFile ), # --contextBufferFilepath=%OUTPUT%
                     # ..\..\..\..\vocon\models\acmod3_%MODELSIZE%_%MODELLANG%_gen_car_f%MODELFREQ%_%MODELVERS%.dat
                     '--modelFilepath=..\\..\\..\\vocon\\models\\acmod3_{}_{}_gen_car_f{}_{}.dat'.format( self.config.get_model_size(),
                                                                                                              lang,
                                                                                                              self.config.get_model_freq(),
                                                                                                              self.config.get_lang_model_vers( lang ),
                                                                                                              ),
                     '--contextBufferSearchTreeType={}'.format( self.config.get_search_tree_type() ), # --contextBufferSearchTreeType=%SEARCHTREETYPE%
                     '--useg2p=true',
                     '--useComputedParameters=true',
                     ]

        try:
            subprocess.check_output( arguments )
        except:
            raise AssertionError( 'Nem sikerült legenerálni a commands.lcf fájlt: "{}"'.format( ' '.join( arguments ) ) )

        return inputFile

    def __generate_house_number_lcf( self, lang ):
        """
        @set INPUT=%MODELLANG%\house_number.bnf
        @set OUTPUT=temp/%MODELLANG%/house_number.lcf
        %PYTHON_TL% "%VOCON3200_INSTALL_PATH%\tools\contextcpl.pyc" -p contextcpl.param --grammarFilepaths=%INPUT% --contextBufferFilepath=%OUTPUT% --modelFilepath=..\..\..\..\vocon\models\acmod3_%MODELSIZE%_%MODELLANG%_gen_car_f%MODELFREQ%_%MODELVERS%.dat --contextBufferSearchTreeType=%SEARCHTREETYPE% --useg2p=true --useComputedParameters=true        
        """
        print( '\n\tcreating the "house_number.lcf" file...' )

        inputFile = os.path.abspath( os.path.join( self.sourceFolderPath, self.config.get_lang_model_lang( lang ), 'house_number.bnf' ) )
        outputFile = os.path.join( self.tempFolderPath, self.config.get_lang_model_lang( lang ), 'house_number.lcf' )

        return self.__generate_lcf( lang, inputFile, outputFile )

    def __create_info_ini( self, lang ):
        """
        ansii a file
        """
        info_ini = self.__open_info_ini( os.path.join( self.tempFolderPath, self.config.get_lang_model_lang( lang ), 'info.ini' ) )

        info_ini.write( '[info]\n' )
        info_ini.write( 'asr_version="{}"\n'.format( self.config.get_engine_ver() ) ) # v3_4F1
        info_ini.write( 'asr_type="{}"\n'.format( self.config.get_asr_type() ) ) # basic
        info_ini.write( 'asr_language="{}"\n'.format( lang.upper() ) ) # ENG
        info_ini.write( 'asr_model_version="{}"\n'.format( self.config.get_lang_model_vers( lang )[1:] ) ) # 1_0_1
        info_ini.write( 'house_number_first="{}"\n'.format( self.config.get_lang_house_number_first( lang ) ) ) # 1

        info_ini.close()

    def __open_info_ini( self, path ):
        info_ini = open( path, "w" )

        return info_ini

    def __create_path2zip( self, lang ):
         path2zip = os.path.abspath( os.path.join( self.full_outputFolderPath,
                                                   '{}_{}_{}.vnb'.format( self.config.get_lang_model_lcid( lang ),
                                                                          self.config.get_engine_ver(),
                                                                          self.config.get_lang_model_lang( lang ),
                                                                          ),
                                                  ) )

         return path2zip

    def __zip( self, lang, path2zip ):
        """
        cd temp/%MODELLANG%
        "C:\\Program Files\\7-Zip\\7z.exe" a ../../out/%MODELLCID%_%ENGINEVERS%_%MODELLANG%.vnb -tzip -mx0 commands.lcf commands.csv house_number.lcf content.nng ../../%MODELLANG%/house_number.lua ../../%MODELLANG%/info.ini
        
        """
        print( '\n\tcreating the zip file...' )

        arguments = [self.config.get_7zip(),
                     'a',
                     path2zip,
                     '-tzip',
                     '-mx0',
                     os.path.join( self.tempFolderPath,
                                   self.config.get_lang_model_lang( lang ),
                                   'commands.lcf',
                                   ),
                     os.path.join( self.tempFolderPath,
                                   self.config.get_lang_model_lang( lang ),
                                   'commands.csv',
                                   ),
                     os.path.join( self.tempFolderPath,
                                   self.config.get_lang_model_lang( lang ),
                                   'house_number.lcf',
                                   ),
                     os.path.join( self.tempFolderPath,
                                   self.config.get_lang_model_lang( lang ),
                                   'content.nng',
                                   ),
                     os.path.abspath( os.path.join( self.sourceFolderPath,
                                                    self.config.get_lang_model_lang( lang ),
                                                    'house_number.lua' ),
                                      ),
                     os.path.join( self.tempFolderPath,
                                   self.config.get_lang_model_lang( lang ),
                                   'info.ini' ),
                     ]

        try:
            subprocess.check_output( arguments )
        except:
            raise AssertionError( 'Nem sikerült legenerálni a commands.lcf fájlt: "{}"'.format( ' '.join( arguments ) ) )

    def __copy_zip2Temp( self, path2zip ):
        print( '\n\tcoping the "{}" zip...'.format( os.path.basename( path2zip ) ) )
        shutil.copy( path2zip, self.tempFolderPath )

    def __remove_generation( self ):
        print( 'removing the "{}" folder from the "_out" folder.'.format() )
        os.rmdir( self.outputFolderPath )


class BNFFileParser():
    def __init__( self ):
        self.rx = re.compile( r"^\<(?P<name>[ \w]+)\>.*!id\((?P<id>\d+)\)" )

    def __open_bnf_file( self, bnf_filePath ):
        if os.path.isfile( bnf_filePath ):
            self.bnf_file = open( bnf_filePath, "r", encoding = 'utf-8' )
        else:
            raise AssertionError( 'Nem lehet megnyitni a bnf fájlt: "{}"'.fromat( os.path.abspath( bnf_filePath ) ) )

    def __open_output_file( self, output_filePath ):
        self.output_file = open( output_filePath, "w", encoding = 'utf-8' )

    def __parser( self ):
        for line in self.bnf_file:
            match = self.rx.search( line )
            if match is not None:
                s = "%s, %s\n" % ( match.group( "id" ), match.group( "name" ) )
#                print( '\n\t{}'.format( s[:-1] ) )
                self.output_file.write( s )

        self.output_file.close()

    def main( self, bnf_filePath, output_filePath ):
        print( '\n\tparsing the "{}" file...'.format( os.path.basename( bnf_filePath ) ) )
        self.__open_bnf_file( bnf_filePath )
        self.__open_output_file( output_filePath )
        self.__parser()


class ConentNNG:
    """Gets a CID (content ID) from the Condor Server based on a received request patter and creates a content.nng file.
    
    get pattern: "cidhttp?subtype=??&lockey=??&name=??"
        the ?? means a data
    http: http://condor/contentbuilder/ext/getnonmapcontentid.php
    subtype: ASR, Voice, etc.
        should be in registered data in the content builder database
        should be one str without "_ ."
    lockey: unique key of the given content
    name: 1_2_3_4 
        the blocks are special for the content type, but the convention is:
            1: SUBTYPE
            2: NAME
            3: SUPPLIER
            4: VERSION
    
            - the numbers of the blocks should be 4, no more or less
            - the block separator should be "_": 1_2_3_4
            - all blocks should be to start with upper case letter (it is in change)
            - the part separator would be "--" into a block (it is your choice)
    
    For the content.nng file creation the latest "ContentNNGGenerator.exe" is needed.
    """
    def __init__( self, contentNNGGeneratorEXEPath, destPath, subType, lockey, name, cryptoKey ):
        self.contentNNGGeneratorEXEPath = contentNNGGeneratorEXEPath    # path to the content.nng generator program
        self.destPath = destPath                                        # destination path of the content.nng
        self.requestData = {"subtype": subType,
                            "lockey": lockey,
                            "name": name,
                            }
        self.cryptoKey = cryptoKey                                      # unique name of a content pack to the generation of the content.nng file
        self.timeStamp = "{:.0f}".format( time.time() )

        self.__request()

    def __request( self ):
        """Requests the CID number from the Conder server and checks its state.
        """
        requestStr = urllib.parse.urlencode( self.requestData ).encode( "UTF-8" )

        try:
            with urllib.request.urlopen( "http://condor/contentbuilder/ext/getnonmapcontentid.php", requestStr ) as page:
                self.cid, self.message = page.read().decode( "UTF-8" ).split( "\n", 1 )

                self.__check()
        except:
            self.cidState = False
            print( "\n!!!Unable to get a CID from the server!!!" )

    def __check( self ):
        """Checks the state of the response that should be contain a real and usable CID number.
        
        The CID number should be a 10 elements number.
        The response could contains request message too.
        
        If the response is not 10 elements number or  the response contains an error message that it is an error.
        """
    # existing content
        if len( self.cid ) == 10 and ( not self.message or self.message == "" ):
            self.cidState = True
            print( "\n\tAn existing Content ID is received." )
    # new content
        elif len( self.cid ) == 10 and self.message and self.message.startswith( "[INF]" ):
            self.cidState = True
            print( "\n\tNew Content ID is created: {} {}".format( self.cid, self.message ) )
    # error
        elif self.message and self.message.startswith( "[ERR]" ):
            self.cidState = False
            print( "\n\tResponse ERROR! Unable to generate the content.nng file from the response:\n{}".format( self.message ) )
    # other unknown case
        else:
            self.cidState = False
            print( "\n\tUnknown response! Unable to generate the content.nng file from the response:\n{}".format( self.message ) )

    def create( self ):
        """Creates the content.nng file to the given path.
        """
        if self.cidState:
            print( '\n\tcreating the "content.nng" file...'.format() )
            arguments = [self.contentNNGGeneratorEXEPath,
                         self.cryptoKey,
                         self.cid,
                         self.timeStamp,
                         os.path.join( self.destPath, 'content.nng' ),
                         ]
            try:
#                subprocess.check_output(arguments)
                subprocess.check_output( arguments )
                return True
            except:
                print( "\n\tUnable to convert the content.nng file!" )
                return False
        else:
            print( "\n\t!!!Unable to generate the content.nng file!!!" )
            return False

class VRContentID( ConentNNG ):
    """Creates a content.nng file based on the given data.
    
    VR content type:
        -VDE (cimkereses, nem Media feladat, hanem DB-s)
            structured: a cim mezoinek kulon-kulon megadva, megadasa
            one shoot: a cim egyben megadva, bemondva
            
        -1S (one shoot, nem Media feladat hanem DB-s)
            -
        -PS (POI kereses)
            -
        -CC (command control)
            ui: iGO menuben maszkalasra
            contact: phone contact
            digit dial: 
    
    Nuance engine type/ver: 
        vocon:
            v3_3
            v3_4
            v3_4F1
            v3_4F2
            
        paklite: 
            ?
        fl:
            ?
    
    VR CID Name convention:
        1_2_3_4: a block-ok "_" szeparaltak,
        a block-on belul a "--" a szeparator,
            1: condorContentName
            2: VR--VRContentType--LangCode
            3: ProviderName-EngineType--EngineVer
            4: iGOBranch--iGOUIName
        
            "condorContentName_VR--VRContentType--LangCode_ProviderName-EngineType--EngineVer_iGOBranch--iGOUIName"
            "ASR_VR--CC--ged_Nuance--vocon--v3-4F1_iGO-GM1-FTEN--ui-fujitsuten"
    
    Subtype: ASR (28)
    name: 1_2_3_4
    lockey: VR_Nuance-vocon-ged
    
    !!!A NUANCE VOCON ENGINE-K TELEPITVE KELL LENNIE AZ ADOG GEPEN AHOL EZ FOG FUTNI!!!
    
    """
    def __init__( self, **kwargs ):
        self.contentNNGGeneratorEXEPath = kwargs["contentGenerator"]
        self.destPath = kwargs["DestPath"]
        self.subType = 28

        kwargs = self.__format( **kwargs )

#        lockey = "VR_Nuance-vocon-ged"
        self.lockey = "VR_{Provider}-{VREngine}-{LangCode}".format( **kwargs )
#        name = "ASR_VR--CC--ged_Nuance--vocon--v3-4F1_iGO-GM1-FTEN--ui-fujitsuten"
        self.name = "ASR_VR--{VRContentType}--{LangCode}_{Provider}--{VREngine}--{VREngineVer}_{iGOBranch}--{iGOUI}".format( **kwargs )
#        cryptoKey = "asr_base_vocon34_ged.vnb"
        self.cryptoKey = "{VRFileName}".format( **kwargs )

        ConentNNG.__init__( self, self.contentNNGGeneratorEXEPath, self.destPath, self.subType, self.lockey, self.name, self.cryptoKey )

    def __format( self, **kwargs ):
        for k, v in kwargs.items():
            if k == "Provider":
                kwargs[k] = self.__replace( v ).title()
            elif k == "VREngine":
                kwargs[k] = self.__replace( v ).lower()
            elif k == "VREngineVer":
                kwargs[k] = self.__replace( v )
            elif k == "VRContentType":
                kwargs[k] = self.__replace( v ).upper()
            elif k == "iGOBranch":
                kwargs[k] = self.__replace( v )
            elif k == "iGOUI":
                kwargs[k] = self.__replace( v ).lower()
            elif k == "LangCode":
                kwargs[k] = self.__replace( v ).lower()
            elif k == "VRFileName":
                kwargs[k] = v.lower()
            elif k == "DestPath":
                pass
            elif k == "contentGenerator":
                pass
            else:
                raise AssertionError( "WTF..." )

        return kwargs

    def __replace( self, v ):
        """Replace all not needed characters like space, underscore, etc. to "-".
        """
        v = re.sub( "[{}{}]".format( string.punctuation, string.whitespace ), "-", v )
        v = re.sub( "--+", "-", v )

        return v


if __name__ == '__main__':
    root = Tk()
    VRContentGenerator( root )
    root.mainloop()
