# -*- coding: utf-8 -*-
"""Membuat web map statis (Leaflet + GeoJSON) dari data KPH Contoh. Penulis: Badar Mubarok Yogaswara
Hanya membuat berkas lokal di folder keluaran/peta_web. Tidak mengunggah apa pun.
Jalankan: python-qgis.bat buat_peta_web.py
"""
import json, math, os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from qgis.core import (QgsApplication, QgsVectorLayer, QgsCoordinateReferenceSystem,
                       QgsVectorFileWriter, QgsCoordinateTransform, QgsCoordinateTransformContext)

AQ = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.abspath(os.path.join(AQ, "..", "..", "..", "data-sintetis"))
OUT = os.path.join(AQ, "keluaran", "peta_web")


def ke_tile(lon, lat, zoom):
    """Nomor ubin XYZ (skema web: x ke timur, y ke selatan) untuk satu titik."""
    n = 2 ** zoom
    x = int((lon + 180.0) / 360.0 * n)
    y = int((1.0 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2.0 * n)
    return x, y


def ekspor(layer_path, nama_layer, berkas):
    lyr = QgsVectorLayer(layer_path, nama_layer, "ogr")
    assert lyr.isValid(), layer_path
    opsi = QgsVectorFileWriter.SaveVectorOptions()
    opsi.driverName = "GeoJSON"
    opsi.fileEncoding = "UTF-8"
    opsi.ct = QgsCoordinateTransform(
        lyr.crs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsCoordinateTransformContext())
    opsi.layerOptions = ["COORDINATE_PRECISION=6", "RFC7946=YES"]
    hasil = QgsVectorFileWriter.writeAsVectorFormatV3(lyr, berkas, QgsCoordinateTransformContext(), opsi)
    assert hasil[0] == QgsVectorFileWriter.WriterError.NoError, hasil
    return lyr.featureCount()


HTML = """<!doctype html>
<html lang="id"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Peta KPH Contoh</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>html,body,#peta{height:100%;margin:0}</style></head>
<body><div id="peta"></div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
var peta = L.map('peta');
fetch('petak.geojson').then(r => r.json()).then(function (d) {
  var lap = L.geoJSON(d, {
    style: {color: '#2B6CB0', weight: 2, fillOpacity: 0.15},
    onEachFeature: function (f, l) {
      l.bindPopup('<b>' + f.properties.ID_Petak + '</b><br>' + f.properties.NAMA_KPH +
                  '<br>' + f.properties.Jenis + ', ' + f.properties.Luas_Ha + ' ha');
    }
  }).addTo(peta);
  peta.fitBounds(lap.getBounds());
});
fetch('hotspot.geojson').then(r => r.json()).then(function (d) {
  L.geoJSON(d, {pointToLayer: function (f, p) {
    return L.circleMarker(p, {radius: 6, color: '#C0392B', fillOpacity: 0.8});
  }}).addTo(peta);
});
</script></body></html>
"""

if __name__ == "__main__":
    app = QgsApplication([], False)
    app.initQgis()
    os.makedirs(OUT, exist_ok=True)
    n1 = ekspor(os.path.join(DATA, "paket-m4", "Petak_KPH.gpkg"), "Petak_KPH", os.path.join(OUT, "petak.geojson"))
    n2 = ekspor(os.path.join(DATA, "paket-data", "Hotspot_Nasional.gpkg"), "Hotspot", os.path.join(OUT, "hotspot.geojson"))
    with open(os.path.join(OUT, "index.html"), "w", encoding="utf-8") as fh:
        fh.write(HTML)
    print("petak:", n1, "hotspot:", n2)
    for b in ("petak.geojson", "hotspot.geojson"):
        d = json.load(open(os.path.join(OUT, b), encoding="utf-8"))
        c = d["features"][0]["geometry"]["coordinates"]
        while isinstance(c[0], list):
            c = c[0]
        print(b, "fitur:", len(d["features"]), "koordinat pertama (lon, lat):", c)
    print("ubin zoom 0 untuk (0,0):", ke_tile(0, 0, 0), "| zoom 1 untuk (0,0):", ke_tile(0, 0, 1),
          "| zoom 10 Jakarta -6.2,106.85:", ke_tile(106.85, -6.2, 10))
    app.exitQgis()
