import json
from CodeGenerator import Generator


class ScreenProcessor:
    def __init__(self, json_file_name, save_as_file_name) -> None:
        self.generator = Generator()
        self.json_file_name = json_file_name
        self.save_as_file_name = save_as_file_name
        self.screen_name = self.json_file_name.split('/')[-1]
        self.screen_name = self.screen_name.split('.')[0]
        self.identifications = []
        self.all_elements = []

    def load_json(self):
        "Reads the json file and returns it as a list of dictionaries."
        with open(self.json_file_name, "r") as screen:
            screen = json.load(screen)

        return screen
    
    def assign_screen_name(self):
        "Calls a re sub funtion and change the screen name in self.screen_name."
        self.generator.re_sub_screen_name(pattern="<<name_of_screen>>", repl=self.screen_name, string=self.generator.screen_name)
        
        return self.generator.screen_name
    
    def assign_screen_class(self):
        "Calls a re sub funtion and change the screen class in self.screen_class."
        self.generator.re_sub_screen_class(pattern="<<name_of_screen>>", repl=self.screen_name, string=self.generator.screen_class)
        
        return self.generator.screen_class


    def generate_python_string(self):
        """Loops through the list in screen and looks for element or identification.
        If it's element, it passes the value to the next function that handles elements.
        The same goes for identification.
        Then it returns the string which contains the code that is later passed into the python file."""
        
        json_screen = self.load_json()
        for index, dictionary in enumerate(json_screen):
            if list(dictionary.keys())[0] == "Element":
                self.add_elements(dictionary)
            elif list(dictionary.keys())[0] == "Identification":
                self.add_identifications(dictionary)
        
        return self.add_strings_together()
    
    def add_strings_together(self):
        "Simply takes all data and put them together."
        screen_name = self.assign_screen_name()
        screen_class = self.assign_screen_class()
        identifications = self.summarize_identifications()
        elements = self.summarize_elements()

        if identifications and elements:
            return screen_name + screen_class + '\n' + '\t' + identifications + '\n' + '\t' + elements
        elif identifications:
            return screen_name + screen_class + '\n' + '\t' + identifications
        elif elements:
            return screen_name + screen_class + '\n' + '\t' + elements
        else:
            return screen_name + screen_class

    def add_elements(self, element_dictionary):
        elements_string = """.add_element(<<element>>(name="<<name>>", <<element_2>>identification_tag=<<identification_tag>>)<<target_screen>>
        <<false_identification_tag>><<true_identification_tag>><<values>><<value_identificators>><<threshold>>) \\"""
        
        elements = []
        target_screen = False
        false_identification_tag = False
        true_identification_tag = False
        values = False
        value_identificators = False
        threshold = False
        element_identification_tag = False

        which_element = element_dictionary["Element"][0]
        elements_string = self.generator.re_sub_strings("<<element>>", which_element, elements_string)

        for index, element in enumerate(element_dictionary["Element"]):
            if isinstance(element, dict) and (list(element.keys())[0] == "identification_tag" or list(element.keys())[0] == "element_identification_tag"):
                if list(element.keys())[0] == "element_identification_tag":
                    element_identification_tag = True
                if element_dictionary["Element"][index][list(element.keys())[0]] == "TextTag":
                    elements.append(self.generator.generate_text_tag(element_dictionary, "Element"))
                
                elif element_dictionary["Element"][index][list(element.keys())[0]] == "IconTag":
                    elements.append(self.generator.generate_icon_tag(element_dictionary, "Element"))
                
                elif element_dictionary["Element"][index][list(element.keys())[0]] == "TextToolTag":
                    elements.append(self.generator.generate_text_tool_tag(element_dictionary, "Element"))
                
                elif element_dictionary["Element"][index][list(element.keys())[0]] == "OrTag":
                    elements.append(self.generator.generate_or_tag(element_dictionary, "Element"))
                
                elif element_dictionary["Element"][index][list(element.keys())[0]] == "PlaceHolderTag":
                    elements.append(self.generator.generate_placeholder_tag(element_dictionary, "Element"))
           
            elif isinstance(element, dict) and list(element.keys())[0] == "name":
                elements_string = self.generator.re_sub_strings("<<name>>", element_dictionary["Element"][index]["name"], elements_string)
            
            elif isinstance(element, dict) and list(element.keys())[0] == "target_screen":
                target_screen = element_dictionary["Element"][index]["target_screen"]
            
            elif isinstance(element, dict) and list(element.keys())[0] == "false_identification_tag":
                false_identification_tag = element_dictionary["Element"][index]["false_identification_tag"]

            elif isinstance(element, dict) and list(element.keys())[0] == "true_identification_tag":
                true_identification_tag = element_dictionary["Element"][index]["true_identification_tag"]
            
            elif isinstance(element, dict) and list(element.keys())[0] == "values":
                values = element_dictionary["Element"][index]["values"]
            
            elif isinstance(element, dict) and list(element.keys())[0] == "value_identificators":
                value_identificators = element_dictionary["Element"][index]["value_identificators"]
            
            elif isinstance(element, dict) and list(element.keys())[0] == "threshold":
                threshold = str(element_dictionary["Element"][index]["threshold"])
        
        if target_screen:
            elements_string = self.generator.re_sub_strings("<<target_screen>>", f', "{target_screen}"', elements_string)
        else:
            elements_string = self.generator.re_sub_strings("<<target_screen>>", "", elements_string)

        elements_string = self.generator.re_sub_strings("<<identification_tag>>", ''.join(elements), elements_string)

        if element_identification_tag:
            elements_string = self.generator.re_sub_strings("<<element_2>>", "element_", elements_string)
        else:
            elements_string = self.generator.re_sub_strings("<<element_2>>", "", elements_string)
        
        if false_identification_tag:
            elements_string = self.generator.re_sub_strings("<<false_identification_tag>>", f', false_identification_tag="{false_identification_tag}"', elements_string)
        else:
            elements_string = self.generator.re_sub_strings("<<false_identification_tag>>", "", elements_string)
        
        if true_identification_tag:
            elements_string = self.generator.re_sub_strings("<<true_identification_tag>>", f', true_identification_tag="{true_identification_tag}"', elements_string)
        else:
            elements_string = self.generator.re_sub_strings("<<true_identification_tag>>", "", elements_string)
        
        if values:
            elements_string = self.generator.re_sub_strings("<<values>>", f', values={values}', elements_string)
        else:
            elements_string = self.generator.re_sub_strings("<<values>>", "", elements_string)
        
        if value_identificators:
            elements_string = self.generator.re_sub_strings("<<value_identificators>>", f', value_identificators={value_identificators}', elements_string)
        else:
            elements_string = self.generator.re_sub_strings("<<value_identificators>>", "", elements_string)
        
        if threshold:
            elements_string = self.generator.re_sub_strings("<<threshold>>", f', threshold={threshold}', elements_string)
        else:
            elements_string = self.generator.re_sub_strings("<<threshold>>", "", elements_string)
        

        self.all_elements.append(elements_string)
        
    
    def add_identifications(self, identification_dictionary):
        "This method is adding the identifications to a list that is later on used for generating python script."

        which_tag = identification_dictionary["Identification"][0]
        
        if which_tag == "TextTag":
            self.identifications.append(self.generator.generate_text_tag(identification_dictionary, "Identification"))
        elif which_tag == "IconTag":
            self.identifications.append(self.generator.generate_icon_tag(identification_dictionary, "Identification")) 
        elif which_tag == "TextToolTag":
            self.identifications.append(self.generator.generate_text_tool_tag(identification_dictionary, "Identification"))
        elif which_tag == "OrTag":
            self.identifications.append(self.generator.generate_or_tag(identification_dictionary, "Identification"))
        elif which_tag == "PlaceHolderTag":
            self.identifications.append(self.generator.generate_placeholder_tag(identification_dictionary, "Identification"))

    def summarize_elements(self):
        if len(self.all_elements) > 0:
            self.all_elements[-1] = self.all_elements[-1][:-2] # Just remove last backslash after last .add_element().
            return '\n\t'.join(self.all_elements)
        return False

    def summarize_identifications(self):
        "This method calls the sub_identification method, which substitutes the tags inside of self.generator.identification."
        if len(self.identifications) > 0:
            identification_string = """.add_identification(\n\t\t<<tags>>) \\"""

            all_identifications_as_string = ', \n\t\t'.join(self.identifications) # This unpacks all elements in list and passes them as strings separated by comma.
            
            identification_string = self.generator.re_sub_strings("<<tags>>", all_identifications_as_string, identification_string)
            
            return identification_string
        return False
