import axipy
from axipy import provider_manager, CoordSystem, Geometry, data_manager, Feature,GeometryType


def cloneFeature(ft:axipy.da.Feature)->axipy.da.Feature:
    items=ft.items()
    geometry=ft.geometry.clone()
    style=ft.style.clone()
    ft_out=Feature()
    for item in items:
        ft_out[item[0]]=item[1]
    ft_out.geometry=geometry
    ft_out.style=style
    return ft_out

def copyTabSpatial(path_table,path_dest,geometry):
    temp_table= provider_manager.open_hidden({'src':path_table})
    if temp_table is None:
        return False
    try:
        schema_source=temp_table.schema
        definition = {'src':path_dest,
                      'schema':schema_source,
                      'hidden':True
        }
        tab_dest=provider_manager.tab.create_open(path_dest, schema_source)
        cont_tab=data_manager.count
        items_text_tab_sel=data_manager.query_hidden('Select * from '+temp_table.name+' Where Str$(obj)="Text"')
        for ft in items_text_tab_sel.items():
            geo_text=ft.geometry
            jkl=0
        geo_bound = geometry.bounds
        item_sel = temp_table.itemsInRect(geo_bound)
        out_ft = []
        for ft in item_sel:
            if ft.geometry.intersects(geometry):
                if ft.geometry.type==GeometryType.Text or ft.geometry.type==GeometryType.Point:
                    out_ft.append(ft)

                else:
                    geo_intersect=ft.geometry.intersection(geometry)
                    if geo_intersect is not None:
                        ft_out=cloneFeature(ft)
                        ft_out.geometry=geo_intersect
                        out_ft.append(ft_out)

        if len(out_ft)>0:
            tab_dest.insert(out_ft)
            tab_dest.commit()
        tab_dest.close()
    except Exception as ex:
        pass
    finally:
        #temp_table.close()
        #tab_dest.close()
        pass

cs4326 = CoordSystem.from_epsg(4326)
wkt='POLYGON((78.59433699999999 54.86970399999999,78.7314735 60.5771058,92.36831829999999 65.5583072,111.591896 62.82098359999999,108.3164285 57.69031679999999,95.6568065 53.7413079,78.59433699999999 54.86970399999999))'
geo=Geometry.from_wkt(wkt,cs4326)
geo_bound=geo.bounds
path_source='E:\\Temp\\TestPointForClip.tab'
#path_source='E:\\Temp\\TestPointForClipMi.TAB'
path_dest='E:\\Temp\\testCopy1.tab'
copyTabSpatial(path_source,path_dest,geo)
