import logging
from pathlib import Path
from typing import Dict

from kedro.framework.session import KedroSession

from actesdataset import EtreeXMLDataSet, BsXMLDataSet, JSONDataSet
from actesdataset import (XMLDataSetCollection, BsXMLDataSetCollection,
                         JSONDataSetCollection, TextDataSetCollection)

logger = logging.getLogger(__name__)

with KedroSession.create() as session:
    context = session.load_context()
#    catalog = context.get_catalog()

def parse_xml_collection(datasetcol: XMLDataSetCollection) -> XMLDataSetCollection:
    "node function entry point, performs batch processing"
    datasets = datasetcol.datasets
    housename = datasetcol._housename
    output_datasets = context.catalog.load(housename + '_xmlcontent')
    outputfolderpath = output_datasets._folderpath
    for dataset_filenamestem, dataset in datasets.items():
        # a manual load is required here, because
        # the dataset **is not** registered in kedro's catalog
        dataset._load()
        output_source_doc = dataset.transform() 
        # set dataset's output filepath
        output_filepath = outputfolderpath / Path(dataset_filenamestem).with_suffix(".pseudoxml")
        output_xmldataset = EtreeXMLDataSet(str(output_filepath), output_datasets.xsltstylesheet)
        # let's create subfolders, if they don't exist
        output_xmldataset_dir = output_filepath.parent
        output_xmldataset_dir.mkdir(parents=True, exist_ok=True)
        # save on file
        output_xmldataset._save(output_source_doc)
        output_datasets.datasets[dataset_filenamestem] = output_xmldataset
    return output_datasets


def make_json_collection(datasetcol: BsXMLDataSetCollection) -> JSONDataSetCollection:
    "node function entry point, performs batch processing"
    datasets = datasetcol.datasets
    housename = datasetcol._housename
    output_datasets = context.catalog.load(housename + '_jsonoutput')
    outputfolderpath = output_datasets._folderpath
    for dataset_filenamestem, dataset in datasets.items():
        # a manual load is required here, because
        # the dataset **is not** registered in kedro's catalog
        dataset._load()
        output_source_doc = dataset.transform() 
        # set dataset's output filepath
        output_filepath = outputfolderpath / Path(dataset_filenamestem).with_suffix(".json")
        output_xmldataset = JSONDataSet(str(output_filepath))
        # let's create subfolders, if they don't exist
        output_xmldataset_dir = output_filepath.parent
        output_xmldataset_dir.mkdir(parents=True, exist_ok=True)
        # save on file
        output_xmldataset._save(output_source_doc)
        output_datasets.datasets[dataset_filenamestem] = output_xmldataset
    return output_datasets

def add_xmlcontent_tojson(jsondoc: JSONDataSetCollection, xmlcontent: TextDataSetCollection) -> JSONDataSetCollection:
    "adds xmlcontent to the json"
    jsondatasets = jsondoc.datasets
    housename = jsondoc._housename
    output_datasets = context.catalog.load(housename + '_fulljsonoutput') 
    outputfolderpath = output_datasets._folderpath
    xmldatasets = xmlcontent.datasets
    for dataset_filenamestem, dataset in jsondatasets.items():
        document = dataset._load()
        output_filepath = outputfolderpath / Path(dataset_filenamestem).with_suffix(".json")
        output_xmldataset = JSONDataSet(str(output_filepath))
        # json dict update with xmlcontent
        if dataset_filenamestem in xmldatasets:
            xmlds = xmldatasets[dataset_filenamestem]
#            xmlds._load()
            document['xmlcontent'] = xmldatasets[dataset_filenamestem]._load()
        else:
            raise KeyError(f"xmlcontent datasets does not have the key : {dataset_filenamestem}")
        # let's create subfolders, if they don't exist
        output_xmldataset_dir = output_filepath.parent
        output_xmldataset_dir.mkdir(parents=True, exist_ok=True)
        # save on file
        output_xmldataset._save(document)
        output_datasets.datasets[dataset_filenamestem] = output_xmldataset
    return output_datasets    
    
