# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.

# %% auto 0
__all__ = ['Client']

# %% ../nbs/00_core.ipynb 3
from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef, RDFS
import pandas as pd

# %% ../nbs/00_core.ipynb 4
class Client():
    def __init__(self):
        pass

    @staticmethod
    def get_prefixes(df):
        sheet_prefix = df

        prefixes = {}

        for index, row in sheet_prefix.iterrows():
            p = row["接頭辞"]
            uri = row["URI"]
            prefixes[p] = uri

            # g.bind(p, uri)

        return prefixes
    
    @staticmethod
    def replace_prefix(text, prefixes):
        for p in prefixes:
            if text.startswith(p + ":"):
                return text.replace(p + ":", prefixes[p])
        return text
    
    @staticmethod
    def main(sheet_df, path, prefixes):
        """
        This function reads a DataFrame, creates a RDF graph, and serializes it in Turtle format.
        
        Args:  
            sheet_df (pd.DataFrame): The input DataFrame containing the data to be converted into RDF.  
            path (str): The path to the output file where the serialized RDF graph will be saved.  
            prefixes (dict): A dictionary of prefixes used in the RDF graph.
        """

        # Rename variable for clarity
        data_frame = sheet_df

        # Initialize an empty RDF graph
        g = Graph()

        # Bind prefixes in the graph
        for p in prefixes:
            g.bind(p, prefixes[p])

        # Get column names from the DataFrame
        cols = data_frame.columns.tolist()

        # Iterate through each row in the DataFrame
        for index, row in data_frame.iterrows():


            # Iterate through each column in the row
            for col in cols:
                if col == "subject":
                    # Skip the row if the "uri" column is empty
                    if pd.isnull(row[col]):
                        continue

                    # Replace the prefix in the value and create a subject URI
                    value = Client.replace_prefix(row[col], prefixes)
                    subject = URIRef(value)
                else:
                    # If the cell is not empty, process it
                    if not pd.isnull(row[col]):
                        col_spl = col.split(" ")
                        p_uri_str = Client.replace_prefix(col_spl[0], prefixes)

                        # Check if there is an option for the value
                        if len(col_spl) > 1:
                            option = col_spl[1]

                            if option == "^^uri":
                                value = Client.replace_prefix(row[col], prefixes)
                                g.add((subject, URIRef(p_uri_str), URIRef(value)))
                            elif option.startswith("@"):
                                g.add((subject, URIRef(p_uri_str), Literal(row[col], lang=option[1:])))
                            else:
                                g.add((subject, URIRef(p_uri_str), Literal(row[col])))

        # 'data/tmp/schema.ttl'
        g.serialize(destination=path, format='turtle')

    @staticmethod
    def create_rdf_from_excel(path, prefix_sheet_name, target_sheet_name, output_path):
        """
        This function reads an Excel file containing RDF data and prefixes, then generates and saves an RDF graph in Turtle format.

        Args:  
            path (str): The path to the input Excel file.  
            prefix_sheet_name (str): The name of the sheet containing prefix data in the Excel file.  
            target_sheet_name (str): The name of the sheet containing RDF data in the Excel file.  
            output_path (str): The path to the output file where the serialized RDF graph will be saved.
        """

        # Read the Excel file into a dictionary of DataFrames
        df = pd.read_excel(path, sheet_name=None)

        # Extract the prefix data and convert it into a dictionary
        sheet_prefix = df[prefix_sheet_name]
        prefixes = Client.get_prefixes(sheet_prefix)

        # Convert the target sheet into an RDF graph and save it in Turtle format
        Client.main(df[target_sheet_name], output_path, prefixes)

