from multiprocessing import Pool
from Word import Word
import multiprocessing

if __name__ == "__main__":
    # Verify dict.txt and input.txt exist
    import os, sys
    from PrimeTest import PrimeTest
    from ChainHashMap import ChainHashMap
    
        # make sure files exist
    if os.path.exists("dict.txt") and os.path.exists("input.txt"):
        # initialize hash table 
        num_words = sum(1 for line in open('dict.txt')) 
        hash_table = ChainHashMap(num_words) 

        # populate hash table with words in dictionary
        for word in open('dict.txt'):
            hash_table[word.strip()] = "" 

        # Custom function for processing
        def check_word(word):
            try:
                hash_table[word.lower()]
                res = word
            except KeyError:
                res = Word(word,hash_table).spellproposals()
            finally:
                return res      

        # Process line and print to stdout
        output = ""
        with Pool(processes = multiprocessing.cpu_count()) as pool:
            for line in open("input.txt"):
                words = line.strip().split(" ")
                # Check if "'" present in words to adjust
                for w in words:
                    # Delete word and add 2 new words to list
                    if("'" in w and w.index("'") != len(w)-1):
                        idx = w.index("'") + 1
                        words.append(w[:idx])
                        words.append(w[idx:])
                        words.remove(w)

                for w in pool.map(check_word, words):
                    output += w + " "
        print(output)
            
    # dict.txt and/or input.txt don't exist
    else:
        print("Error: could not find necessary files, \
                'dict.txt' and 'input.txt'")
        sys.exit(1)

    """DEBUGGING"""
    if("debug" in sys.argv):
        # Check efficiency of hash table
        coll = num_words - hash_table.buckets
        print("DEBUG", 
                "Num entries in ht: " + str(hash_table.len()), 
                "Num words in dict: " + str(num_words), 
                "Num of buckets in ht: " + str(hash_table.buckets),
                "Max bucket size: " + str(hash_table.maxbucketsize),
                "Num of collisions: " + str(coll), 
                "% of collisions: " + str((coll / num_words) * 100),
                "Prime number used for ht size: " + str(hash_table.size),
                sep="\n")
        
        # make a couple access to ht
        print("\n", "3 first words supposed to be in ht")
        try:
            words = ["aboveboard", "battened", "bowdlerise", "notinht",
                    "shouldreturnkeyerror", "shitfacecockmaster"]
            for w in words:
                print(hash_table[w])
        except Exception as e:
            print(e.args, "is not in dictionary")
            


