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):

    with conn.cursor() as desa:
        desa.execute(f"SELECT id, desa, kecamatan FROM geo_data_kelurahan order by desa ASC")
        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, db_tipe, remark, point_id, point_name), '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 and type_id = 2) ), '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, db_tipe, remark, point_id), '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")
        
        luast_b = request.POST.get("luastanah_b")
        luasb_b = request.POST.get("luasbangunan_b")
        tinggi_b = request.POST.get("tinggibangunan_b")
        pemilik_b = request.POST.get("pemilik_b")
        
        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, luas_bangunan=%s, luas_tanah=%s, tinggi_bangunan=%s, pemilik='%s' WHERE id = %s"""% (co_edit,name_b, info_b, desa_b, kec_b, kab_b, pro_b, namafile, luasb_b, luast_b, tinggi_b, pemilik_b, 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':
        nama_desa = request.GET.get("id_desa_search")
        
        nama_desa = nama_desa.split(",")[0]
        with conn.cursor() as bts:
            bts.execute("""
                        SELECT
                            st_asgeojson ( ST_ExteriorRing ( the_geom ) ) AS erings 
                        FROM
                            ( SELECT ( ST_Dump ( geom ) ).geom AS the_geom FROM geo_data_kelurahan WHERE desa = '%s' ) as foo
                        """% nama_desa)
            batas = bts.fetchall()
            # batas_desa = json.loads(batas)
            line_o = []
            for i in batas:
                o_pol1 = ''
                o_poly = []
                
                for x in json.loads(i[0])['coordinates']:
                    o_pol1 += (f'{x[0]},{x[1]}""')
                
                o_pol2 = o_pol1.replace('""1',',1')

                o_poly.append(o_pol2.replace('""',''))
                
                line_o.append(o_poly)
        
        with conn.cursor() as desa:
            desa.execute("""
                        SELECT
                            ST_AsGeoJson ( ST_centroid ( geom ) ) 
                        FROM
                            geo_data_kelurahan 
                        WHERE
                            desa = '%s'"""% nama_desa)
            lat_lng = desa.fetchall()
        
        with conn.cursor() as bang:
            bang.execute("""SELECT
                                json_build_object (
                                    'type',
                                    'Feature',
                                    'properties',
                                    ( buildings.ID, buildings.NAME, buildings.information ),
                                    'administrasi',
                                    (
                                        buildings.address_1,
                                        buildings.address_2,
                                        buildings.address_3,
                                        buildings.provinsi,
                                        buildings.alamat,
                                        buildings.luas_bangunan,
                                        buildings.luas_tanah,
                                        buildings.tinggi_bangunan,
                                        buildings.gambar,
                                        buildings.pemilik 
                                    ),
                                    'geometry',
                                    ST_AsGeoJSON ( buildings.geom :: geometry ) :: json 
                                ) 
                            FROM
                                geo_bangunan buildings
                                JOIN geo_data_kelurahan desa ON st_intersects (  ST_SetSRID(desa.geom, 0), buildings.geom ) 
                            WHERE
                                desa.desa = '%s'"""% nama_desa)
            
            bangunan = bang.fetchall()
            
            polygon_o = []
            info_polygon = []
            tinggi_pol = []
            for i in bangunan:
                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'])
            
        
                
            # for i in batas:
            #     o_batas = ''
            #     o_poly_batas = []
            #     for x in i[0]['geometry']['coordinates'][0][0]:
            #         o_batas += (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'])
        
        lat = json.loads(lat_lng[0][0])['coordinates'][0]
        lng = json.loads(lat_lng[0][0])['coordinates'][1]
                        
        respon={'polygon_o':polygon_o,'tinggi_pol':tinggi_pol, 'info_polygon': info_polygon, 'lat':lat, 'lng':lng, 'line_o':line_o}
        return Response(respon)
    
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')
    tipedb = request.GET.get('tipedb')
    poin = request.GET.get('poin')
    remark = request.GET.get('remark')
    info = request.GET.get('info')
    atalam = request.GET.get('alamat')
    lb = request.GET.get('lb')
    lt = request.GET.get('lt')
    tibang = request.GET.get('tb')
    ltbang = request.GET.get('ltb')
    kilimep = request.GET.get('pemilik')
    namafile = "None"
    
    latlng = po_create.split("],[")[0]
    print(p_create)
    print(latlng)
    
    if name == "":
        name = "None"
    else:
        name = name
        
    if info == "":
        info = "None"
    else:
        info = info
        
    if lb == "":
        lb = 0
    else:
        lb = lb
        
    if lt == "":
        lt = 0
    else:
        lt = lt
    
    if tipedb == "":
        tdb = "bangunan"
    else:
        tdb = tipedb
    
    if poin == "":
        pointopeto = 0
    else:
        pointopeto = poin
    
    if remark == "":
        rem = "bangunan"
    else:
        rem = remark
    
    if atalam == "":
        alamat = "None"
    else:
        alamat = atalam
    print(alamat)
    try:
        if tibang == "" and ltbang != "":
            tb = ltbang*3
        elif tibang == "" and ltbang == "":
            tb = 0
            ltb = 0
        else:
            tb = tibang
    except:
        tb = 0
    print(tb)
    try:
        if ltbang == "" and tibang != "":
            ltb = int(int(tibang)/3)
        elif tibang == "" and ltbang == "":
            tb = 0
            ltb = 0
        else:
            ltb = ltbang
    except:
        ltb = 0
    if kilimep == "":
        pemilik = "unnamed"
    else:
        pemilik = kilimep
    print(pemilik)
    
    
    # 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, lantai, gambar, pemilik, point_id, type_id, remark, db_tipe) VALUES (ST_GeomFromEWKT('SRID=0;MULTIPOLYGON(((%s)))'), '%s', '%s', 'new', '%s', '%s', '%s', '%s', '%s', '0', '%s', '%s', '%s', '%s', '%s', '%s', %s, '1', '%s', '%s')"""% (p_create, name, info, alamat, administrasi[0], administrasi[1], administrasi[2], administrasi[3], lb, lt, tb, ltb, namafile, pemilik, pointopeto, rem, tdb ))
    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)

import re
@api_view(('POST',))
def createjalan(request):
    polyline = request.POST.get('polyline')
    name_jalan = request.POST.get('name_jalan')
    panjang_jalan = request.POST.get('panjang_jalan')
    lebar_jalan = request.POST.get('lebar_jalan')
    tipe_jalan = request.POST.get('tipe_jalan')
    img_jalan = request.FILES.get('gambar')
    
    panjang_jalan = re.sub('[^0-9.]+', '', str(panjang_jalan))
    if lebar_jalan == '':
        lebar_jalan = 0
    print(panjang_jalan)
    coord = json.loads(str(polyline))
    print(coord)
    
    try:
        if coord['features'][0]['geometry']['type'] == 'LineString':
            for co in coord['features']:
                ll = str(co["geometry"]['coordinates'])
                ll += ll
            ll = ll.replace(", "," ")
            ll = ll.replace("]][[","),(")
            ll = ll.replace("] [",", ")
            ll = ll.replace("]]",")")
            ll = ll.replace("[[","(")

            coordinat = f'MULTILINESTRING({ll})'
    except:
        if coord['geometry']['type'] == 'LineString':
            
            ll = str(coord["geometry"]['coordinates'])
                
            ll = ll.replace(", "," ")
            ll = ll.replace("]][[","),(")
            ll = ll.replace("] [",", ")
            ll = ll.replace("]]",")")
            ll = ll.replace("[[","(")

            coordinat = f'MULTILINESTRING({ll})'
    fss_p = FileSystemStorage(location='static/image/jalan/')
    try:
        format = (img_jalan.name).split(".")
        num = random.randrange(1, 10000000000000)
        ngambar = f"{name_jalan}_{num}.{format[-1:][0]}"
        ngambar = ngambar.replace(" ","-")
        filename_p = fss_p.save(ngambar, img_jalan)
        url_p = fss_p.url(filename_p)
    except:
        ngambar = 'None'
    
    try:
                
        with conn.cursor() as jalan:
            jalan.execute("""INSERT INTO geo_jalan(geom, namrjl, panjang_jalan, lebar_jalan, remark, gambar) VALUES (ST_GeomFromEWKT('SRID=4326;%s'), '%s', %s, %s,'%s','%s')"""% (coordinat, name_jalan, panjang_jalan, lebar_jalan, tipe_jalan, ngambar))
        conn.commit()
        
        data = 'SUCCESS'
        info = 'data telah diperbaharui'
        status = 0
    except:
        data = 'Opss..!!'
        info = 'Hubungi Developer'
        status = 1
    
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)

@api_view(('GET',))
def changetipe(request):
    tipe_point = request.GET.get('tipe')
    
    if tipe_point == 'bangunan':
            tipepoint = [['Rumah'],['Ruko'],['Pabrik'],['Pasar/Swalayan']]
    
    if tipe_point == 'kantor_administrasi':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_kantor_administrasi""")
            tipepoint = point.fetchall()
        
    if tipe_point == 'layanan_kesehatan':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_layanan_kesehatan""")
            tipepoint = point.fetchall()

    if tipe_point == 'puskesmas':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_puskesmas""")
            tipepoint = point.fetchall()
        
    if tipe_point == 'rumah_sakit':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_rumah_sakit""")
            tipepoint = point.fetchall()
        
    if tipe_point == 'sarana_ibadah':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_sarana_ibadah""")
            tipepoint = point.fetchall()
        
    if tipe_point == 'sarana_pendidikan':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_sarana_pendidikan""")
            tipepoint = point.fetchall()
            
    if tipe_point == 'cagar_budaya':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_cagar_budaya""")
            tipepoint = point.fetchall()

    if tipe_point == 'spbu':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_spbu""")
            tipepoint = point.fetchall()
            
    if tipe_point == 'stasiun':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_stasiun""")
            tipepoint = point.fetchall()
            
    if tipe_point == 'terminal_bus':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_terminal_bus""")
            tipepoint = point.fetchall()
            
    if tipe_point == 'gardu_listrik':
        with conn.cursor() as point:
            point.execute("""SELECT DISTINCT remark FROM geo_gardu_listrik""")
            tipepoint = point.fetchall()
    print(tipepoint)
    respon = {'result':tipepoint}
    return Response(respon)

@api_view(('GET',))
def changejenis(request):
    tipe_point = request.GET.get('tipe')
    jenis_point = request.GET.get('jenis')
    if tipe_point == 'bangunan':
        tipepoint1 = [['0','-']]
    else:
        with conn.cursor() as point:
            point.execute("""SELECT id, namobj FROM geo_%s where remark = '%s'"""% (tipe_point, jenis_point))
            tipepoint1 = point.fetchall()
    respon = {'result':tipepoint1}
    return Response(respon)

@api_view(('POST',))
def createpoint(request):
    gambar = request.FILES.get('gambar')
    co_point = request.POST.get('point')
    name_create_point = request.POST.get('name_create_point')
    tipe_point = request.POST.get('tipe_point')
    info_create_point = request.POST.get('info_create_point')
    alamat_create_point = request.POST.get('alamat_create_point')
    luas_bangunan_point = request.POST.get('luas_bangunan_point')
    luas_tanah_point = request.POST.get('luas_tanah_point')
    tinggi_bangunan_point = request.POST.get('tinggi_bangunan_point')
    lantai_point = request.POST.get('lantai_point')
    pemilik_point = request.POST.get('pemilik_point')
    
    
    coord = json.loads(str(co_point))
    
    coordinat = coord['geometry']['coordinates']
    
    fss_p = FileSystemStorage(location='static/img/image/')
    try:
        format = (gambar.name).split(".")
        num = random.randrange(1, 10000000000000)
        ngambar = f"{name_create_point}_{num}.{format[-1:][0]}"
        ngambar = ngambar.replace(" ","-")
        filename_p = fss_p.save(ngambar, gambar)
        url_p = fss_p.url(filename_p)
    except:
        ngambar = 'None'
    
    # 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_bangunan = '%s', luas_tanah = '%s', tinggi_bangunan = '%s', perangkat = '%s', gambar = '%s' where id = %s
    try:
        if tipe_point == 'administrasi':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_kantor_administrasi(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 5,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
            
        if tipe_point == 'layanankesehatan':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_layanan_kesehatan(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 6,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()

        if tipe_point == 'puskesmas':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_puskesmas(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 7,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
            
        if tipe_point == 'rumahsakit':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_rumah_sakit(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 8,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
            
        if tipe_point == 'saranaibadah':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_sarana_ibadah(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 9,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
            
        if tipe_point == 'saranapendidikan':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_sarana_pendidikan(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 10,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()

        if tipe_point == 'cagarbudaya':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_cagar_budaya(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 3,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
        
        if tipe_point == 'spbu':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_spbu(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 3,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
            
        if tipe_point == 'stasiun':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_stasiun(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 3,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
            
        if tipe_point == 'terminalbus':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_terminal_bus(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 3,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
            
        if tipe_point == 'gardulistrik':
            with conn.cursor() as point:
                point.execute("""INSERT INTO geo_gardu_listrik(geom, namobj, remark, luas_tanah, alamat, perangkat, type_id, gambar) VALUES (st_geomfromgeojson('{"type":"Point", "coordinates":%s, "crs":{"type":"name","properties":{"name":"EPSG:4326"}}}'), '%s','%s', %s, '%s', '%s', 3,'%s')"""% (coordinat, name_create_point, info_create_point, luas_tanah_point, alamat_create_point, pemilik_point, ngambar))
            conn.commit()
        
        data = 'SUCCESS'
        info = 'data telah diperbaharui'
        status = 0
    except:
        data = 'Opss..!!'
        info = 'Hubungi Developer'
        status = 1
    
    respon={'data':data, 'info': info, 'status':status}
    return Response(respon)