from pathlib import Path
from zipfile import ZipFile
import io
def readXmlFromFile(path_file):
    source_xml=None
    with io.open(path_file, 'r', encoding='utf8') as f:
        source_xml = f.read()
    return source_xml
class ZipSource:
    def __init__(self,path_zip_file):
        self.__zip = None
        self.__zip= ZipFile(path_zip_file,"r")
        self.__path_file=path_zip_file

    def close(self):
        if self.__zip is not None:
            self.__zip.close()
        self.__zip=None

    def __del__(self):
        if self.__zip is not None:
            self.__zip.close()
        self.__zip=None
    @property
    def files(self,ext_file='.xml'):
        if self.__zip is None:
            return None
        list_info_files = self.__zip.infolist()
        list_file_name = []
        for file_info in list_info_files:
            name_file = file_info.filename.encode('cp437').decode('cp866')
            ext=str(Path(name_file).suffix)
            if not (ext.lower()==ext_file.lower()):
                continue
            list_file_name.append({'source': file_info.filename, 'encode': name_file,'cls':self})
        if len(list_file_name)==0:
            return None
        return list_file_name
    def getSource(self,name):
        data_zip = self.__zip.read(name)
        data_zip_str = data_zip.decode('utf-8')
        return data_zip_str
class DataSourceXml:
    def __init__(self):
        self.__count=0
        self.__source=[]
        self.__source_cls=[]
    def build(self,list_files):
        for source in list_files:
            ext=Path(source).suffix
            if ext.lower()=='.xml':
                self.__source.append(source)
                continue
            if ext.lower()=='.zip':
                cls=ZipSource(source)
                list_from_zip=cls.files
                if list_from_zip is None:
                    continue
                self.__source_cls.append(cls)
                self.__source.extend(list_from_zip)
                continue
        self.__count=len(self.__source)
        return len(self.__source)
    @property
    def count(self):

        return self.__count
    def getSource(self,id):
        if not(id<self.__count):
            return None,None
        item_source=self.__source[id]
        if isinstance(item_source,str):
            source_text=readXmlFromFile(item_source)
            return item_source,source_text
        source_xml=item_source['cls'].getSource(item_source['source'])
        return item_source['encode'],source_xml
    def clear(self):
        if len(self.__source_cls)>0:
            for cls_zip in self.__source_cls:
                cls_zip.close()
        self.__source_cls.clear()
        self.__source.clear()




