from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response
from django.db import connection as conn

# Create your views here.
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def search_auto(request):
    nama_desa = request.GET.get('namadesa')
    with conn.cursor() as desa:
        desa.execute(f"SELECT id, desa, kecamatan FROM geo_data_kelurahan WHERE desa ILIKE '{nama_desa}%' order by desa ASC limit 5")
        all = desa.fetchall()    
        
    data = {'nama_des':all}
    return Response(data)

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def tuplah(request):
    with conn.cursor() as desa:
        desa.execute(f"SELECT json_build_object('type', 'Feature', 'legend', a.legenda,'geometry', ST_AsGeoJSON( st_intersection(a.geom, b.geom):: geometry) :: json) from geo_tuplah a, geo_prov_kab b")
        all = desa.fetchall()    
        
    data = {'tuplah':all}
    return Response(data)

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def building(request):
    if request.method == 'GET':
        wetan = request.GET.get("wetan")
        kulon = request.GET.get("kulon")
        lor = request.GET.get("lor")
        kidul = request.GET.get("kidul")
        # lat = request.GET.get("lat")
        # lng = request.GET.get("lng")
        
        # kulon lor, wetan lor, wetan kidul, kulon kidul, kulon lor
        with conn.cursor() as buldings:
            buldings.execute("SELECT json_build_object('type', 'Feature', 'properties', (id, name, information, 'gen'), 'administrasi',(address_1, address_2, address_3, provinsi, 'no'), 'geometry', ST_AsGeoJSON(geom :: geometry) :: json) FROM geo_bangunan WHERE st_intersects(geom,'SRID=0;POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))')"% (kulon, lor, wetan, lor, wetan, kidul, kulon, kidul, kulon, lor))
            prov_res = buldings.fetchall()
            
            polbang = []        
            for i in prov_res:
                i[0]['properties']['f2'] = i[0]['properties']['f2'].replace("'"," ")
                polbang.append(i[0])
            
        data = {'gen':prov_res}
        return Response(data)
    
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def jalan(request):
    if request.method == 'GET':
        wetan = request.GET.get("wetan")
        kulon = request.GET.get("kulon")
        lor = request.GET.get("lor")
        kidul = request.GET.get("kidul")
        # lat = request.GET.get("lat")
        # lng = request.GET.get("lng")
        
        # kulon lor, wetan lor, wetan kidul, kulon kidul, kulon lor
        with conn.cursor() as jalan:
            jalan.execute("SELECT json_build_object ('type', 'Feature', 'properties', ( id, namrjl ), 'geometry', ST_AsGeoJSON ( st_intersection(geom, 'SRID=4326;POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))') :: geometry ) :: json ) FROM geo_jalan WHERE st_intersects(geom,'SRID=4326;POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))')"% (kulon, lor, wetan, lor, wetan, kidul, kulon, kidul, kulon, lor, kulon, lor, wetan, lor, wetan, kidul, kulon, kidul, kulon, lor))
            prov_res = jalan.fetchall()
                                
        data = {'gen':prov_res}
        return Response(data)
    
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def sungai(request):
    if request.method == 'GET':
        wetan = request.GET.get("wetan")
        kulon = request.GET.get("kulon")
        lor = request.GET.get("lor")
        kidul = request.GET.get("kidul")
        # lat = request.GET.get("lat")
        # lng = request.GET.get("lng")
        
        # kulon lor, wetan lor, wetan kidul, kulon kidul, kulon lor
        with conn.cursor() as sungai:
            sungai.execute("SELECT json_build_object ('type', 'Feature', 'properties', ( a.id, a.namobj ), 'geometry', ST_AsGeoJSON ( st_intersection(a.geom, b.geom) :: geometry ) :: json ) FROM geo_sungai a, geo_prov_kab b")
            prov_res = sungai.fetchall()
                                
        data = {'gen':prov_res}
        return Response(data)
    
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpoly(request):
    if request.method == 'GET':
        id_poly = request.GET.get("id_poly")                   
        with conn.cursor() as buldings:
            buldings.execute("SELECT json_build_object('type', 'Feature', 'properties', (id, name, information, 'osm'), 'administrasi',(address_1, address_2, address_3, provinsi, 'no'), 'geometry', ST_AsGeoJSON(geom :: geometry) :: json) FROM geo_bangunan WHERE id = %s"% int(id_poly))
            build = buldings.fetchall()
        
        return Response(build[0][0])

import json    
@api_view(('POST',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def validatedit(request):
    if request.method == 'POST':
        name_b = request.POST.get("name_b")
        info_b = request.POST.get("info_b")
        desa_b = request.POST.get("desa_b")
        kec_b = request.POST.get("kec_b")
        kab_b = request.POST.get("kab_b")
        pro_b = request.POST.get("pro_b")
        
        id_poly = request.POST.get("id_poly")
        polygon = request.POST.get("polygon")
        cood_edit = json.loads(polygon)
            
        co_edit = cood_edit['geometry']['coordinates']
        print(id_poly, name_b, info_b, polygon)
        with conn.cursor() as buldings:
            buldings.execute("""UPDATE geo_bangunan set geom = st_geomfromgeojson('{"type":"MultiPolygon", "coordinates":[%s]}'),name='%s',information='%s',address_1='%s', address_2 = '%s', address_3 = '%s', provinsi='%s' WHERE id = %s"""% (co_edit,name_b, info_b, desa_b, kec_b, kab_b, pro_b, int(id_poly)))
        conn.commit()
            
        data = {'status':'Success'}
        return Response(data)
    
@api_view(('POST',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def hapus(request):
    if request.method == 'POST':
        id_poly = request.POST.get("id_poly")

        with conn.cursor() as buldings:
            buldings.execute("""DELETE from geo_bangunan where id = %s"""% int(id_poly))
        conn.commit()
            
        data = {'status':'Success'}
        return Response(data)
    
    


@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def hasilsearch(request):
    if request.method == 'GET':
        id_desa = request.GET.get("id_desa_search")

        with conn.cursor() as kel:
            kel.execute("SELECT json_build_object('type', 'Feature', 'administrasi', (kode_desa, desa, kecamatan, kab_kota, provinsi, jumlah_pen, jumlah_kk, luas_desa),'penduduk', (pria, wanita, belum_kawin, kawin, cerai_hidup, cerai_mati, wajib_ktp, islam, kristen, khatolik, hindu, budha, konghucu, kepercayaan_lain, u0, u5, u10, u15, u20, u25, u30, u35, u40, u45, u50, u55, u60, u65, u70, u75),'pekerjaan_pendidikan', (tidak_sekolah, belum_tamat, tamat_sd, sltp, slta, diploma_i, diploma_ii, diploma_iv, strata_ii, strata_iii, tidak_bekerja, aparatur_pemerintah, tenaga_pendidik, wiraswasta, pertanian, tenaga_kesehatan, pensiunan, pegawai, tentara, kepolisian, pedagang, petani, peternak, nelayan, karyawan, buruh, pembantu, tukang, pendeta, pastor, ustadz, dosen, guru, pilot, pengacara, notaris, arsitek, akuntan, konsultan, dokter, bidan, perawat, psikiater, sopir, lainnya),'geometry', ST_AsGeoJSON(geom :: geometry) :: json) from geo_data_kelurahan where id = %s"% int(id_desa))
            kel_res_ = kel.fetchall()
            
        kel_res = []
        for i in kel_res_:
            kel_res.append(i[0])

        data = {'result':kel_res}
        return Response(data)