
from decimal import Context
from django.shortcuts import render, redirect
# from django.views.generic import ListView, DetailView,  DeleteView, UpdateView, CreateView
from django.views import View, generic
from django.db import connection as conn
import urllib

def editkelurahan(request):
    if request.method == 'GET':
        kode_dagri = request.GET.get('kode_dagri')
        
        with conn.cursor() as edit_poly:
            edit_poly.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), 'poi',(jml_puskesma, jml_sekolah, jml_sarib),'geometry', ST_AsGeoJSON(geom :: geometry) :: json) from geo_data_kelurahan where kode_desa = '%s'"% kode_dagri)
            res_edit_poly = edit_poly.fetchall()
        
        la = []
        lo = []
        for i in res_edit_poly[0][0]['geometry']['coordinates'][0][0]:
            la.append(i[0])
            lo.append(i[1])
            
        avg_la = sum(la)/len(la)
        avg_lo = sum(lo)/len(lo)
        
        desa = res_edit_poly[0][0]['administrasi']['f2']
        kec = res_edit_poly[0][0]['administrasi']['f3']
        kab = res_edit_poly[0][0]['administrasi']['f4']
        prov = res_edit_poly[0][0]['administrasi']['f5']
        context = {'desa':desa, 'kec':kec, 'kab':kab, 'prov':prov,'result_poly': res_edit_poly[0][0], 'avg_la':avg_la, 'avg_lo':avg_lo}
        return render (request, 'maps/e.html', context)