import jc
import json
#from pyodide.ffi import to_js, create_proxy
from pyscript import when, window, document
import js
from header_replacement import * 
from tailor_for_jc_input import *


#import pyodide
#from js import createObject
x=5.105

#createObject(create_proxy(globals()), "pyodideGlobals")

def give_y(event):
    global y
    y=6.105
    return y

def print_globals(event): #for inspection only
    print(globals())

def translate_codetable_2(codetable):

    initial_colIndex = js.colStartIndex
    initial_colIndex+1
    #print(js.colStartIndex)
    #global return_result
    #textarea = document.querySelector("#reverse")
    
    # Set the textarea value to the incoming codetable
    #textarea.value = codetable

    # normalize the raw input codetable -> return tailored table, screenshot headers, and modified headers for future exchange
    tailored_codetable, screenshot_header_list, anti_snake_case_list = tailor_for_jc_input(codetable)

    #jc.parse() return a list of dicts with all keys are headers
    jc_json = jc.parse('asciitable', tailored_codetable, raw=True, quiet=True)

    #restore the keys(headers) to screenshot headers
    restored_jc_json = restore_keys(jc_json, screenshot_header_list, anti_snake_case_list)

    #json_recreate() return a list of dicts with keys (col1, col2,...)
    concat_list = json_recreate(restored_jc_json)
    
    #convert to json format (string) for transfering to JS
    json_string = json.dumps(concat_list)
    return_result = json_string
    
    return return_result

def translate_codetable(event):
    global return_result
    textarea = document.querySelector("#reverse2")
    codetable = textarea.value
    #print(codetable)
    output_div = document.querySelector("#output")
    jc_json = jc.parse('asciitable', codetable)
    return_result = json_recreate(jc_json)
    #print('return_result', return_result)
    return return_result
    #output_div.innerText = return_result

def json_recreate(json_output):

    initial_colIndex = js.colStartIndex #query start colindex from global js

    all_keys = json_output[0].keys()
    row_header = {}
    for index, key in enumerate(all_keys, initial_colIndex):
        column = {f"col{index}": key}
        row_header.update(column)
    #print('row_header', row_header) #{'col0': '0', 'col1': 'selector', 'col2': 'example', 'col3': 'description'}

    new_list = []
    for _ in range(len(json_output)):
        rows = {}
        for index, key in enumerate(all_keys, initial_colIndex):
            jc_dict = json_output[_]
            value = jc_dict[key]
            # if new_list:
            #     print(new_list[-1])
            #     print(jc_dict['0'])
            #     print(key)
            #     print(new_list[-1][f"col{index}"])
            # if new_list and jc_dict['0'] is None:
            #     original_word = new_list[-1][f"col{index}"]
            #     print('original_word', original_word)
            #     new_word = str(original_word or '') +'\n'+ str(value or '')
            #     new_list[-1][f"col{index}"] = new_word
                    
            # else:
            column = {f"col{index}": value}
            rows.update(column)

        if set(rows.values()) == {None}: #rows.values() = [None, ..., None]
            continue
        else:
            new_list.append(rows)
            
    new_list.insert(0, row_header)

    #print(new_list) #[{'col0': '0', 'col1': 'selector',..., 'counting from the last children'}]

    #concatenate words
    concat_list = []
    for dict_row in new_list:
        if concat_list and dict_row[f"col{initial_colIndex}"] is None:  #'col0' is entry numbers
            #print(dict_row)                            # {'col0': None, 'col1': None, 'col2': None, 'col3': 'counting from the last children'}
            for i, (k, v) in enumerate(dict_row.items(), 0):
                original_words = concat_list[-1][k]
                new_words = str(original_words or '') +'\n'+ str(v or '')
                concat_list[-1][k] = new_words
        else:
            concat_list.append(dict_row)
        
    #print(concat_list) #[{'col0': '0',..., {'col0': '3\n', 'col1': ':nth-last-child(n)\n', 'col2': 'p:nth-last-child(2)\n',...,parent,\ncounting from the last children'}]

    #Turn all remaining None to ''
    concat_list = [{k: (v if v is not None else '') for k, v in row.items()} for row in concat_list]

    # Remove all last \n
    for dict_row in concat_list:
        for i, (k, v) in enumerate(dict_row.items(), 0):
            if v and v[-1] == '\n':
                dict_row[k] = v.rstrip('\n')
    #print(concat_list) #[{'col0': '0',..., {'col0': '3', 'col1': ':nth-last-child(n)', 'col2': 'p:nth-last-child(2)',...,parent,\ncounting from the last children'}]

    #Remove 'col0'
    for dict_row in concat_list:
        if 'col0' in dict_row:
            dict_row.pop('col0')

    #print(concat_list)  #[{'col1': 'selector', 'col2': 'example,...,parent,\ncounting from the last children'}]

    #Convert to json format to transfer to javascript
    #json_string = json.dumps(concat_list)

    # Print the JSON string
    #print(json_string)  #[{"col1": "selector", "col2": "example",...,parent,\ncounting from the last children"}]

    return concat_list

# Function to get shared data
def get_shared_data():
    return shared_data

def translate_codetable_simple(codetable):
    #global return_result
    #textarea = document.querySelector("#reverse")
    
    # Set the textarea value to the incoming codetable
    #textarea.value = codetable

    # Use the codetable to perform whatever processing you need
    
    jc_json = jc.parse('asciitable', codetable)
    

    json_string = json.dumps(jc_json)
    return_result = json_string
    
    return return_result