import overpy
from A04Convertion_geojson_adm import get_geojson
from A01Test import export_geojson
import os

class OsmConnection:
    def __init__(self):
        pass

    def conectosm_coords(self, osmtype, osmsubtype, coords, doc):
        lat1=coords[0]
        lon1=coords[1]
        lat2=coords[2]
        lon2=coords[3]

        api = overpy.Overpass(url='http://172.22.33.187:8015/api/interpreter')
        query= '''
        (   node('{}','{}','{}','{}')['{}'='{}'];
            way('{}','{}','{}','{}')['{}'='{}'];
            rel('{}','{}','{}','{}')['{}'='{}'];);
            (._;>;);
            out;
        '''.format( lat1, lon1, lat2, lon2, osmtype, osmsubtype,
                    lat1, lon1, lat2, lon2, osmtype, osmsubtype,
                    lat1, lon1, lat2, lon2, osmtype, osmsubtype)
        q = api.query(query)
        export_geojson(q, doc, osmsubtype)


    def conectosm(self, osmtype, osmsubtype, doc):
        api = overpy.Overpass()
        query= '''
        area["ISO3166-1"="ES"]->.search;
        (   node(area.search)['{}'='{}'];
            way(area.search)['{}'='{}'];
            rel(area.search)['{}'='{}'];);
        out body;
        >;
        out skel qt;
        '''.format(osmtype, osmsubtype,osmtype, osmsubtype,osmtype, osmsubtype)
        q = api.query(query)
        export_geojson(q, doc, osmsubtype)

    def conectosm_cca(self, osmtype, osmsubtype, doc1, cca):
        #ca=['AN','AR','AS','CN','CB','CL','CM','CT','CE','EX','GA','IB','RI','MD','MC','NC','PV','VC']
        ca=cca
        for cai in ca:
            doc= doc1+'_'+cai
            api = overpy.Overpass()
            query= '''
            area["ISO3166-2"="ES-{}"]->.search;
            (   node(area.search)['{}'='{}'];
                way(area.search)['{}'='{}'];
                rel(area.search)['{}'='{}'];);
            out body;
            >;
            out skel qt;
            '''.format( cai, osmtype, osmsubtype,osmtype, osmsubtype,osmtype, osmsubtype)
            q = api.query(query)
            export_geojson(q, doc, osmsubtype)
        


