from django.http.response import Http404
from django.shortcuts import redirect, render
from rest_framework import status
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response
from django.core.files.storage import FileSystemStorage
from django.core.files.base import ContentFile, File
import base64
import json
from PIL import Image
from django.contrib.auth.decorators import login_required, user_passes_test
from django.utils.decorators import method_decorator

from django.db import connection as conn

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

# from django.utils import six
import six
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import user_passes_test
from django.http import HttpResponse, HttpResponseNotFound


def group_required(group, login_url=None, raise_exception=False):
    def check_perms(user):

        if isinstance(group, six.string_types):
            groups = (group, )
        else:
            groups = group

        if user.groups.filter(name__in=groups).exists() or user.is_superuser:
            return True

        if raise_exception:
            print('raise')
            raise PermissionDenied("dilarang")

        return False

    return user_passes_test(check_perms, login_url=login_url)


import random

@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.id, a.legenda, st_area(a.geom::geography), a.gambar) ,'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), 'administrasi',(address_1, address_2, address_3, provinsi, alamat, luas_bangunan, luas_tanah, tinggi_bangunan, gambar, pemilik), '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")
        print(kulon, lor, wetan, lor, wetan, kidul, kulon, kidul, kulon, lor, kulon, lor, wetan, lor, wetan, kidul, kulon, kidul, kulon, lor)

        with conn.cursor() as jalan:
            jalan.execute("SELECT json_build_object ('type', 'Feature', 'properties', ( gj.ID, namrjl, st_length ( gj.geom :: geography ), gj.lebar_jalan, gj.remark, gj.gambar,(SELECT ARRAY_AGG ( '' || id || ',' || tgl_perbaikan || '' order by tgl_perbaikan DESC ) FROM tbl_perbaikan WHERE id_object = gj.ID ) ), 'geometry', ST_AsGeoJSON ( st_intersection(gj.geom, 'SRID=4326;POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))') :: geometry ) :: json ) FROM geo_jalan gj WHERE st_intersects(gj.geom,'SRID=4326;POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))') GROUP BY gj.id"% (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 editjalan(request):
    if request.method == 'GET':
        idjalan = request.GET.get("idjalan")

        with conn.cursor() as jalan:
            jalan.execute("SELECT json_build_object ('geometry', ST_AsGeoJSON (geom :: geometry ) :: json ) FROM geo_jalan WHERE id = %s"% idjalan)
            prov_res = jalan.fetchall()
                                
        data = {'jalan':prov_res[0][0]}
        return Response(data)

@api_view(('POST',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))

def editjalanvalid(request):
    file = request.FILES.get('file')
    idjalan = request.POST.get('idjalan')
    namajalan = request.POST.get('namajalan')
    panjangjalan = request.POST.get('panjangjalan')
    tipejalan = request.POST.get('tipejalan')
    lebarjalan = request.POST.get('lebarjalan')
    cordi = request.POST.get('cord')
    cord = json.loads(cordi)
    
    # fss = FileSystemStorage(location='static/image/jalan/')
    # try:
    #     format = (file.name).split(".")
    #     num = random.randrange(1, 10000000000000)
    #     namafile = f"{idjalan}_{num}.{format[-1:][0]}"
    #     filename = fss.save(namafile, file)
    #     url = fss.url(filename)
    # except:
    #     num = random.randrange(1, 10000000000000)
    #     namafile = file.name
    #     filename = fss.save(namafile, file)
    #     url = fss.url(filename)
    
    # try:
    with conn.cursor() as desa:
        desa.execute("""UPDATE geo_jalan set geom = st_setsrid(st_geomfromgeojson('{"type":"MultiLineString", "coordinates":[%s]}'),4326), namrjl = '%s', panjang_jalan = %s, lebar_jalan = %s, remark = '%s' where id=%s"""%(cord['geometry']['coordinates'], namajalan, panjangjalan, lebarjalan, tipejalan, int(idjalan)))
    conn.commit()
        
    data = 'SUCCESS'
    info = 'data telah diperbaharui'
    status = 0
    # except:
    #     data = 'NOT SUCCESS'
    #     info = 'Hubungi Orang Server'
    #     status = 1
    
    respon={'data':data, 'info':info, 'code':status}
    return Response(respon)


@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, alamat, luas_bangunan, luas_tanah, tinggi_bangunan, gambar, pemilik), 'geometry', ST_AsGeoJSON(geom :: geometry) :: json) FROM geo_bangunan WHERE id = %s"% int(id_poly))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointka(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_kantor_administrasi A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom) 
                                WHERE a.is_deleted = 0 and a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointlk(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_layanan_kesehatan A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointpks(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_puskesmas A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointrs(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_rumah_sakit A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointsi(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_sarana_ibadah A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointsp(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_sarana_pendidikan A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointspbu(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_spbu A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointst(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_stasiun A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointgl(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_gardu_listrik A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointtr(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                    json_build_object (
                                        'type',
                                        'Feature',
                                        'administrasi',
                                        (
                                            A.namobj,
                                            A.remark,
                                            A.alamat,
                                            A.luas_bangunan,
                                            A.luas_tanah,
                                            A.satuan_luas_bangunan,
                                            A.satuan_luas_tanah,
                                            A.gambar,
                                            A.tinggi_bangunan,
                                            A.perangkat,
                                            A.tipe_gambar,
                                            b.kabupaten,
                                            c.kecamatan,
                                            d.desa,
                                            a.luas,
                                            a.id
                                        ),
                                        'geometry',
                                        ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                    ) 
                                FROM
                                    geo_terminal_bus A 
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            build = buldings.fetchall()
        
        return Response(build[0][0])

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def editpointcb(request):
    if request.method == 'GET':
        id_point = request.GET.get("id_point")                   
        with conn.cursor() as buldings:
            buldings.execute("""SELECT
                                        json_build_object (
                                            'type',
                                            'Feature',
                                            'administrasi',
                                            (
                                                A.namobj,
                                                A.remark,
                                                A.alamat,
                                                A.gambar,
                                                A.perangkat,
                                                A.tipe_gambar,
                                                b.kabupaten,
                                                c.kecamatan,
                                                d.desa,
                                                a.luas,
                                                a.id
                                            ),
                                            'geometry',
                                            ST_AsGeoJSON ( A.geom :: geometry ) :: json 
                                        ) 
                                    FROM
                                        geo_cagar_budaya A  
                                    JOIN geo_prov_kab b ON st_intersects ( A.geom, b.geom )
                                    JOIN geo_data_kecamatan c ON st_intersects(A.geom, c.geom)
                                    join geo_data_kelurahan d on st_intersects(A.geom, d.geom)
                                WHERE a.id = %s"""% int(id_point))
            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")
        gmb_b = request.POST.get("gambar")
        
        id_poly = request.POST.get("id_poly")
        polygon = request.POST.get("polygon")
        print(polygon)
        cood_edit = json.loads(polygon)
            
        co_edit = cood_edit['geometry']['coordinates']
        print(co_edit,name_b, info_b, desa_b, kec_b, kab_b, pro_b, id_poly)

        file = request.FILES.get('file')
        fss = FileSystemStorage(location='static/image/bangunan/')

        try:
            try:
                format = (file.name).split(".")
                num = random.randrange(1, 10000000000000)
                namafile = f"{name_b}_{num}.{format[-1:][0]}"
                filename = fss.save(namafile, file)
                url = fss.url(filename)
            except:
                namafile = gmb_b
            print(co_edit,name_b, info_b, desa_b, kec_b, kab_b, pro_b, namafile, int(id_poly))
            
            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', gambar = '%s', is_deleted = 0 WHERE id = %s"""% (co_edit,name_b, info_b, desa_b, kec_b, kab_b, pro_b, namafile, int(id_poly)))
            conn.commit()
            
            data = 'SUCCESS'
            info = 'data telah diperbaharui'
            status = 0
            
        except:
            data = 'SORRY'
            info = 'hubungi orang terdekat'
            status = 1
            
        respon = {
            'data':data, 
            'info':info, 
            'code':status,
        }
        print(respon)
            
        return Response(respon)
    
@api_view(('POST',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def hapus(request):
    if request.method == 'POST':
        try:
            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 = 'SUCCESS'
            info = 'data telah diperbaharui'
            status = 0
            
        except:
            data = 'SORRY'
            info = 'hubungi orang terdekat'
            status = 1
            
        respon = {
            'data':data, 
            'info':info, 
            'code':status,
        }
        print(respon)
            
        return Response(respon)
@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)
    
import random
        
@api_view(('POST',))
@method_decorator(login_required(login_url='/login/'))
def editkependudukan(request):
    if request.method == 'POST':
        file = request.FILES.get('file')
        coordinate = request.POST.get('coordinate')
        coord_new = json.loads(coordinate)
        
        ketket = ['kelurahan', 'kecamatan', 'kabupaten', 'provinsi', 'luasdesa', 'jumlahpenduduk', 'jumlahkk', 'jumlahlakilaki', 'jumlahperempuan', 'belumkawin', 'kawin', 'ceraihidup', 'ceraimati', 'wajibktp', 'islam', 'kristen', 'katolik', 'hindu', 'budha', 'konghucu', 'kepercayaanlain', 'u0', 'u5', 'u10', 'u15', 'u20', 'u25', 'u30', 'u35', 'u40', 'u45', 'u50', 'u55', 'u60', 'u65', 'u70', 'u75', 'tidaksekolah', 'belumtamat', 'tamatsd', 'tamatsltp', 'tamatslta', 'diplomai', 'diplomaiii', 'diplomaiv', 'strataii', 'strataiii', 'tidakbekerja', 'aparaturpemerintah', 'tenagapendidik', 'wiraswasta', 'pertanian', 'tenagakesehatan', 'pensiunan', 'pegawai', 'tentara', 'kepolisian', 'dosen', 'guru', 'pilot', 'pedagang', 'petani', 'peternak', 'nelayan', 'karyawan', 'buruh', 'pembantu', 'tukang', 'pendeta', 'pastor', 'ustadz', 'pengacara', 'notaris', 'arsitek', 'akuntan', 'dokter', 'bidan', 'perawat', 'psikiater', 'sopir', 'lainnya', 'kodekelurahan']
        
        list_ketek = []
        for i in ketket:
            list_ketek.append(request.POST.get(i))
            # locals()
            
        kelurahan, kecamatan, kabupaten, provinsi, luasdesa, jumlahpenduduk, jumlahkk, jumlahlakilaki, jumlahperempuan, belumkawin, kawin, ceraihidup, ceraimati, wajibktp, islam, kristen, katolik, hindu, budha, konghucu, kepercayaanlain, u0, u5, u10, u15, u20, u25, u30, u35, u40, u45, u50, u55, u60, u65, u70, u75, tidaksekolah, belumtamat, tamatsd, tamatsltp, tamatslta, diplomai, diplomaiii, diplomaiv, strataii, strataiii, tidakbekerja, aparaturpemerintah, tenagapendidik, wiraswasta, pertanian, tenagakesehatan, pensiunan, pegawai, tentara, kepolisian, dosen, guru, pilot, pedagang, petani, peternak, nelayan, karyawan, buruh, pembantu, tukang, pendeta, pastor, ustadz, pengacara, notaris, arsitek, akuntan, dokter, bidan, perawat, psikiater, sopir, lainnya, kodekelurahan = list_ketek
        
        fss = FileSystemStorage(location='static/image/kelurahan/')
        try:
            format = (file.name).split(".")
            num = random.randrange(1, 10000000000000)
            namafile = f"{kelurahan}_{kodekelurahan}_{num}.{format[-1:][0]}"
            filename = fss.save(namafile, file)
            url = fss.url(filename)
        except:
            num = random.randrange(1, 10000000000000)
            namafile = f"{kelurahan}_{kodekelurahan}_{num}.jpg"
            filename = fss.save(namafile, file)
            url = fss.url(filename)
        
        
            
        try:
            with conn.cursor() as buldings:
                buldings.execute("""UPDATE geo_data_kelurahan set geom = st_setsrid(st_geomfromgeojson('{"type":"MultiPolygon", "coordinates":[%s]}'),4326),desa = '%s', kecamatan = '%s', kab_kota = '%s', provinsi = '%s', luas_desa = %s, jumlah_pen = %s, jumlah_kk = %s, pria=%s, wanita = %s, belum_kawin = %s, kawin = %s, cerai_hidup = %s, cerai_mati = %s, wajib_ktp = %s, islam = %s, kristen = %s, khatolik = %s, hindu = %s, budha = %s, konghucu = %s, kepercayaan_lain = %s, u0 = %s, u5 = %s, u10 = %s,u15 = %s, u20 = %s, u25 = %s, u30 = %s, u35 = %s, u40 = %s, u45 = %s, u50 = %s, u55 = %s, u60 = %s, u65 = %s, u70 = %s, u75 = %s, tidak_sekolah = %s, belum_tamat = %s, tamat_sd = %s, sltp = %s, slta = %s, diploma_i = %s, diploma_ii = %s, diploma_iv = %s, strata_ii = %s, strata_iii = %s, tidak_bekerja = %s, aparatur_pemerintah = %s, tenaga_pendidik = %s, wiraswasta = %s, pertanian = %s, tenaga_kesehatan = %s, pensiunan = %s, pegawai = %s, tentara = %s, kepolisian = %s, dosen = %s, guru = %s, pilot = %s, pedagang = %s, petani = %s, peternak = %s, nelayan = %s, karyawan = %s, buruh = %s, pembantu = %s, tukang = %s, pendeta = %s, pastor = %s, ustadz = %s, pengacara = %s, notaris = %s, arsitek = %s, akuntan = %s, dokter = %s, bidan = %s, perawat = %s, psikiater = %s, sopir = %s, lainnya = %s, gambar = '%s' WHERE kode_desa = '%s'"""% (coord_new['geometry']['coordinates'],kelurahan, kecamatan, kabupaten, provinsi, luasdesa,jumlahpenduduk,jumlahkk,jumlahlakilaki,jumlahperempuan,belumkawin,kawin,ceraihidup,ceraimati, wajibktp,islam,kristen,katolik,hindu,budha,konghucu,kepercayaanlain,u0,u5,u10,u15,u20,u25,u30,u35,u40,u45,u50,u55,u60,u65,u70,u75, tidaksekolah, belumtamat, tamatsd, tamatsltp, tamatslta, diplomai, diplomaiii, diplomaiv, strataii, strataiii, tidakbekerja, aparaturpemerintah, tenagapendidik, wiraswasta, pertanian, tenagakesehatan, pensiunan, pegawai, tentara, kepolisian, dosen, guru, pilot, pedagang, petani, peternak, nelayan, karyawan, buruh, pembantu, tukang, pendeta, pastor, ustadz, pengacara, notaris, arsitek, akuntan, dokter, bidan, perawat, psikiater, sopir, lainnya, namafile, kodekelurahan))
            conn.commit()
            
            with conn.cursor() as kependuduk:
                kependuduk.execute("""SELECT kode_desa, desa, kecamatan, kab_kota, provinsi, luas_desa, jumlah_pen, jumlah_kk, 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, 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, dosen, guru, pilot, pedagang, petani, peternak, nelayan, karyawan, buruh, pembantu, tukang, pendeta, pastor, ustadz, pengacara, notaris, arsitek, akuntan, dokter, bidan, perawat, psikiater, sopir, lainnya, gambar FROM geo_data_kelurahan WHERE kode_desa = '%s'"""% kodekelurahan)
                data_kependuduk = kependuduk.fetchall()      
                     
            data = 'SUCCESS'
            info = 'data telah diperbaharui'
            status = 0
        except:
            data = 'NOT SUCCESS'
            info = 'Hubungi Orang Server'
            status = 1
            
        respon={'data':data, 'info':info, 'code':status, 'penduduk':data_kependuduk[0]}
        data = data_kependuduk[0]
        return Response(respon)

@api_view(('POST',))
def editrumahsakit(request):
    idrs = request.POST.get('idrs')
    namars = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luastanah = request.POST.get('luastanah')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')
    
    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namars}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar
    
    with conn.cursor() as editrs:
        editrs.execute("""update geo_rumah_sakit set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s', alamat = '%s', remark = '%s', luas_tanah = '%s', perangkat = '%s', gambar = '%s' where id = %s"""%(co_edit, namars, alamat, remark, luastanah, perangkat, namafile, idrs))
    conn.commit()    
    
    with conn.cursor() as hasledit:
        hasledit.execute("SELECT id, namobj, alamat, remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, json_build_object('type', 'Feature', 'geometry', ST_AsGeoJSON(geom :: geometry) :: json) from geo_rumah_sakit where id = %s"% idrs)
        hasil_editrs = hasledit.fetchall()
    
    data = {'status':'Success'}
    data = 'SUCCESS'
    info = 'data telah diperbaharui'
    status = 0
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('POST',))
def editcagarbudaya(request):
    idcagar = request.POST.get('idcb')
    namobj = request.POST.get('namobj')
    luas = request.POST.get('luas')
    remark = request.POST.get('remark')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')
        
    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar
    
    with conn.cursor() as editcagar:
        editcagar.execute("""update geo_cagar_budaya set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s', alamat = '%s', remark = '%s', luas = '%s', perangkat = '%s', gambar = '%s' where id = %s"""% (co_edit, namobj, alamat, remark, luas, perangkat, namafile, idcagar))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj, alamat, remark, luas, gambar, perangkat from geo_cagar_budaya where id = %s"""% idcagar)
        hasileditcagar = hasiledit.fetchall()
    
    data = hasileditcagar[0]
    return Response(data)

@api_view(('POST',))
def editkantoradmin(request):
    idkantor = request.POST.get('id')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luat_tanah = request.POST.get('luastanah')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'Bpk'
    elif perangkat == '':
        perangkat = 'Bpk'
    else:
        perangkat = request.POST.get('perangkat')
    
    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']

    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar

    with conn.cursor() as editka:
        editka.execute("""update geo_kantor_administrasi set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas_tanah = %s, perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luat_tanah, perangkat, alamat, namafile, idkantor))
    conn.commit()
    
    data = {'status':'Success'}
    data = 'SUCCESS'
    info = 'data telah diperbaharui'
    status = 0
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('POST',))
def deletekantoradmin(request):
    idkantor = request.POST.get('id')
    try:
        with conn.cursor() as editka:
            editka.execute("""update geo_kantor_administrasi set is_deleted = 1 where id = %s"""%(idkantor))
        conn.commit()    
        
        
        data = {'status':'Success'}
        data = 'SUCCESS'
        info = 'data telah diperbaharui'
        status = 0
    except:
        data = 'Sorry'
        info = 'Dalam Perbaikan'
        status = 1
    
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('POST',))
def editlayanankesehatan(request):
    idlakes = request.POST.get('id')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luat_tanah = request.POST.get('luastanah')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')
    
    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']

    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar
    
    with conn.cursor() as editka:
        editka.execute("""update geo_layanan_kesehatan set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas_tanah = %s, perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luat_tanah, perangkat, alamat, namafile, idlakes))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj,  remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, alamat from geo_layanan_kesehatan where id = %s"""% idlakes)
        hasileditkantor = hasiledit.fetchall()
    
    data = {'status':'Success'}
    data = 'SUCCESS'
    info = 'data telah diperbaharui'
    status = 0
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('POST',))
def editpuskesmas(request):
    idpus = request.POST.get('idpus')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luat_tanah = request.POST.get('luastanah')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')
    
    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']

    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar

    with conn.cursor() as editrs:
        editrs.execute("""update geo_puskesmas set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s', remark = '%s', luas_tanah = '%s', perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luat_tanah, perangkat, alamat, namafile, idpus))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj,  remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, alamat from geo_puskesmas where id = %s"""% idpus)
        hasileditkantor = hasiledit.fetchall()
    
    data = {'status':'Success'}
    data = 'SUCCESS'
    info = 'data telah diperbaharui'
    status = 0
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('POST',))
def editibadah(request):
    idsarib = request.POST.get('idsi')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luat_tanah = request.POST.get('luastanah')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')
    
    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar

    with conn.cursor() as editrs:
        editrs.execute("""update geo_sarana_ibadah set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas_tanah = '%s', perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luat_tanah, perangkat, alamat, namafile, idsarib))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj,  remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, alamat from geo_sarana_ibadah where id = %s"""% idsarib)
        hasileditkantor = hasiledit.fetchall()
    
    data = {'status':'Success'}
    data = 'SUCCESS'
    info = 'data telah diperbaharui'
    status = 0
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('POST',))
def editsekolah(request):
    idsekolah = request.POST.get('idsp')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luat_tanah = request.POST.get('luastanah')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')
    
    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar

    with conn.cursor() as editrs:
        editrs.execute("""update geo_sarana_pendidikan set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas_tanah = '%s', perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luat_tanah, perangkat, alamat, namafile, idsekolah))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj,  remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, alamat from geo_sarana_ibadah where id = %s"""% idsekolah)
        hasileditkantor = hasiledit.fetchall()
    
    data = hasileditkantor[0]

    data = {'status':'Success'}
    data = 'SUCCESS'
    info = 'data telah diperbaharui'
    status = 0
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('POST',))
def editspbu(request):
    idspbu = request.POST.get('idspbu')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luas_bangunan = request.POST.get('luasbangunan')
    luat_tanah = request.POST.get('luastanah')
    tinggi_bangunan = request.POST.get('tinggibangunan')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')

    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar

    with conn.cursor() as editrs:
        editrs.execute("""update geo_spbu set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas_bangunan = '%s', luas_tanah = '%s', tinggi_bangunan = '%s', perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luas_bangunan, luat_tanah, tinggi_bangunan, perangkat, alamat, namafile, idspbu))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj,  remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, alamat from geo_spbu where id = %s"""% idspbu)
        hasileditkantor = hasiledit.fetchall()
    
    data = hasileditkantor[0]

    return Response(data)

@api_view(('POST',))
def editstasiun(request):
    idstasiun = request.POST.get('idst')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luas_bangunan = request.POST.get('luasbangunan')
    luat_tanah = request.POST.get('luastanah')
    tinggi_bangunan = request.POST.get('tinggibangunan')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')

    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar

    with conn.cursor() as editrs:
        editrs.execute("""update geo_stasiun set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas_bangunan = '%s', luas_tanah = '%s', tinggi_bangunan = '%s', perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luas_bangunan, luat_tanah, tinggi_bangunan, perangkat, alamat, namafile, idstasiun))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj,  remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, alamat from geo_stasiun where id = %s"""% idstasiun)
        hasileditkantor = hasiledit.fetchall()
    
    data = hasileditkantor[0]

    return Response(data)

@api_view(('POST',))
def editterminal(request):
    idterm = request.POST.get('idtr')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luas = request.POST.get('luas')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    elif alamat == '':
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
        
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    elif perangkat == '':
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')

    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar

    with conn.cursor() as editrs:
        editrs.execute("""update geo_terminal_bus set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas = '%s', perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luas, perangkat, alamat, namafile, idterm))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj, remark, luas, perangkat, gambar, alamat from geo_terminal_bus where id = %s"""% idterm)
        hasileditkantor = hasiledit.fetchall()
    
    data = hasileditkantor[0]

    return Response(data)

@api_view(('POST',))
def editgardu(request):
    idgardu = request.POST.get('idgl')
    namobj = request.POST.get('namobj')
    remark = request.POST.get('remark')
    luas_bangunan = request.POST.get('luasbangunan')
    luat_tanah = request.POST.get('luastanah')
    tinggi_bangunan = request.POST.get('tinggibangunan')
    gambar = request.POST.get('gambar')
    alamat = request.POST.get('alamat')
    if alamat is None:
        alamat = 'alamat'
    else:
        alamat = request.POST.get('alamat')
    perangkat = request.POST.get('perangkat')
    if perangkat is None:
        perangkat = 'bpk'
    else:
        perangkat = request.POST.get('perangkat')

    point = request.POST.get("point")
    cood_edit = json.loads(point)
        
    co_edit = cood_edit['geometry']['coordinates']
    
    file = request.FILES.get('file')
    fss = FileSystemStorage(location='static/img/image/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{namobj}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        # print(file.name)
        url = fss.url(filename)
    except:
        namafile = gambar


    with conn.cursor() as editrs:
        editrs.execute("""update geo_gardu_listrik set geom = st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), namobj = '%s',  remark = '%s', luas_bangunan = '%s', luas_tanah = '%s', tinggi_bangunan = '%s', perangkat = '%s', alamat = '%s', gambar = '%s' where id = %s"""%(co_edit, namobj, remark, luas_bangunan, luat_tanah, tinggi_bangunan, perangkat, alamat, namafile, idgardu))
    conn.commit()    
    
    with conn.cursor() as hasiledit:
        hasiledit.execute("""select namobj, remark, luas_bangunan, luas_tanah, tinggi_bangunan, perangkat, gambar, alamat from geo_gardu_listrik where id = %s"""% idgardu)
        hasileditkantor = hasiledit.fetchall()
    
    data = hasileditkantor[0]

    return Response(data)

@api_view(('GET',))
@group_required(('Dinas Pekerjaan Umum dan Penataan Ruang', 'Dinas Perumahan dan Kawasan Permukiman', 'Dinas Lingkungan Hidup'), login_url='/')
def edittuplah(request):
    idtuplah = request.GET.get('idtuplah')

    try:
        with conn.cursor() as desa:
            desa.execute(f"SELECT json_build_object('type', 'Feature', 'legend', (a.id, a.legenda, st_area(a.geom::geography), a.gambar) ,'geometry', ST_AsGeoJSON( st_intersection(a.geom, b.geom):: geometry) :: json) from geo_tuplah a, geo_prov_kab b where a.id=%s"% idtuplah)
            all = desa.fetchall()    
            
        data = 'SUCCESS'
        info = 'data telah diperbaharui'
        status = 0
    except:
        data = 'Sorry'
        info = 'Anda Dilarang Akses Link ini'
        status = 1
        
    respon = {
        'data':data, 
        'info':info, 
        'code':status,
        'tuplah':all[0][0]
    }
        
    return Response(respon)

@api_view(('POST',))
@group_required(('Dinas Pekerjaan Umum dan Penataan Ruang', 'Dinas Perumahan dan Kawasan Permukiman', 'Dinas Lingkungan Hidup'),login_url='/')
def edittuplahvalid(request):
    file = request.FILES.get('file')
    idtuplah = request.POST.get('idtuplah')
    cordi = request.POST.get('cord')
    cord = json.loads(cordi)
    
    fss = FileSystemStorage(location='static/image/tuplah/')
    try:
        format = (file.name).split(".")
        num = random.randrange(1, 10000000000000)
        namafile = f"{idtuplah}_{num}.{format[-1:][0]}"
        filename = fss.save(namafile, file)
        url = fss.url(filename)
    except:
        namafile = "NONE"
        
    try:
        with conn.cursor() as desa:
            desa.execute("""UPDATE geo_tuplah set geom = st_setsrid(st_geomfromgeojson('{"type":"MultiPolygon", "coordinates":[[%s]]}'),4326), gambar = '%s' where id=%s"""%(cord['geometry']['coordinates'][0], namafile, int(idtuplah)))
        conn.commit()
            
        data = 'SUCCESS'
        info = 'data telah diperbaharui'
        status = 0
    except:
        data = 'Sorry'
        info = 'Hubungi Developer'
        status = 1
        
    
    
    respon={'data':data, 'info':info, 'code':status}
    return Response(respon)

@api_view(('GET',))
def maps3d(request):
    lattt = request.GET.get('latt')
    longg = request.GET.get('loog')
    
    print(lattt, type(longg))
    with conn.cursor() as gp3:
        gp3.execute("""select json_build_object('type', 'Feature', 'properties', (id, name, information), 'administrasi',(address_1, address_2, address_3, provinsi, alamat, luas_bangunan, luas_tanah, tinggi_bangunan, gambar, pemilik), 'geometry', ST_AsGeoJSON(geom :: geometry) :: json) from geo_bangunan WHERE ST_DistanceSphere(geom, ST_MakePoint(%s,%s)) <= 400 LIMIT 1000"""%(float(longg), float(lattt)))
        polygon_buildings = gp3.fetchall()
        
        polygon_o = []
        info_polygon = []
        tinggi_pol = []
        for i in polygon_buildings:
            o_pol1 = ''
            o_poly = []
            for x in i[0]['geometry']['coordinates'][0][0]:
                o_pol1 += (f'{x[0]},{x[1]}""')
            
            o_pol2 = o_pol1.replace('""1',',1')

            o_poly.append(o_pol2.replace('""',''))
            
            polygon_o.append(o_poly)
            tinggi_pol.append(i[0]['administrasi']['f8'])
            info_polygon.append(i[0]['properties']['f1']) 
                    
    respon={'polygon_o':polygon_o,'tinggi_pol':tinggi_pol, 'info_polygon': info_polygon}
    return Response(respon)

@api_view(('GET',))
def createbang(request):
    poly_create = request.GET.get('polygon')
    p_create = poly_create.replace('"','')
    po_create = p_create.replace(', ','],[')
    
    name = request.GET.get('name')
    info = request.GET.get('info')
    alamat = request.GET.get('alamat')
    lb = request.GET.get('lb')
    lt = request.GET.get('lt')
    tb = request.GET.get('tb')
    pemilik = request.GET.get('pemilik')
    namafile = "None"
    
    latlng = po_create.split("],[")[0]
    
    try:
        with conn.cursor() as kel:
            kel.execute("SELECT desa, kecamatan, kab_kota, provinsi FROM geo_data_kelurahan WHERE st_intersects(geom, 'SRID=4326;POINT(%s)'::geometry)"% latlng)
            adm = kel.fetchall()
            
        administrasi = adm[0]
                
        with conn.cursor() as buldings:
            buldings.execute("""INSERT INTO geo_bangunan(geom, name, information, sumber, alamat, address_1, address_2, address_3, provinsi, no, luas_bangunan, luas_tanah, tinggi_bangunan, gambar, pemilik) VALUES (ST_GeomFromEWKT('SRID=0;MULTIPOLYGON(((%s)))'), '%s', '%s', 'new', '%s', '%s', '%s', '%s', '%s', '0', '%s', '%s', '%s', '%s', '%s')"""% (p_create, name, info, alamat, administrasi[0], administrasi[1], administrasi[2], administrasi[3], lb, lt, tb, namafile, pemilik ))
        conn.commit()
        data = {'status':'Success'}
        
        data = 'SUCCESS'
        info = 'data telah diperbaharui'
        status = 0
    except:
        data = 'Sorry'
        info = 'Dalam Perbaikan'
        status = 1
    
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

# @api_view(('GET',))
