import os
import tempfile

from axipy import provider_manager, data_manager

catalog_temp_files=[]
catalog_tem_tab=[]
def close_table(name_tab):
    if len(catalog_temp_files)==0:
        return
    index_del=None
    for i,tab in enumerate(catalog_temp_files):
        if tab['name']==name_tab:
            index_del=i
            #provider_manager.tab.remove_table_files(tab['path'])
            break

    if index_del is not None:
        catalog_tem_tab.append(catalog_temp_files[index_del]['path'])
        del catalog_temp_files[index_del]

def update_catalog(info):
    if len(catalog_tem_tab)==0:
        return
    if info['operation']=='removed':
        for temp in catalog_tem_tab:
            try:
                provider_manager.tab.remove_table_files(temp)
            except:
                pass
        #catalog_temp_files.clear()

data_manager.removed.connect(close_table)
data_manager.updated.connect(update_catalog)
def create_temp_tab_name(prefix='axi_'):
    temp_name = next(tempfile._get_candidate_names())
    temp_name=prefix+temp_name+".tab"

    temp_folder=tempfile._get_default_tempdir()
    path_tem_tab=os.path.join(temp_folder,temp_name)
    return path_tem_tab

class temp_table_manager():
    @staticmethod
    def create_table(definition_tab):
        #temp = tempfile.NamedTemporaryFile(prefix='axi_temp_')
        path_temp_tab=create_temp_tab_name()
        definition_tab['src']=path_temp_tab
        temp_tab=provider_manager.create_open(definition_tab)
        temp_tab.is_temporary=True
        catalog_temp_files.append({'tab':temp_tab,'name':temp_tab.name,'path':path_temp_tab})
        jkl=0
    @staticmethod
    def close(tab):
        if len(tab)==0:
            return
