## ----message=FALSE------------------------------------------------------------
library(geoarrowWidget)
library(nanoarrow)
library(geoarrow)
library(listviewer)
library(wk)
library(htmlwidgets)

### generate some random wk points data ========================================
n = 1e2
dat = data.frame(
  id = 1:n
  , fillColor = hcl.colors(n)
  , radius = sample.int(15, n, replace = TRUE)
  , geom = xy(
    x = runif(n, -160, 160)
    , y = runif(n, -40, 40)
    , crs = wk_crs_projjson("EPSG:4326")
  )
)


## -----------------------------------------------------------------------------
fl = tempfile()
dir.create(fl)
path = file.path(
  fl
  , "test.arrow"
)

interleaved = TRUE

data_stream = as_nanoarrow_array_stream(
  dat
  , geometry_schema = infer_geoarrow_schema(
    dat
    , coord_type = ifelse(interleaved, "INTERLEAVED", "SEPARATE")
  )
  , schema = infer_nanoarrow_schema(dat)
)

data_stream$get_schema()

write_nanoarrow(data_stream, path)


## -----------------------------------------------------------------------------
wgt = jsonedit(listdata = list(""), elementId = "lv-example")
wgt = attachGeoarrowDependencies(widget = wgt)
wgt = attachData(widget = wgt, file = path, name = "mydata")


## -----------------------------------------------------------------------------
js_code = htmlwidgets::JS(
  'function (el, x, data) {

        // find data attachment in document
        
        let attachment = document.getElementById(data.name + "-geoarrowWidget-attachment");
        
        // find listviewer jsonedit element in document and delete current contents
        
        let jse = document.getElementById("lv-example");
        jse.innerHTML = null;

        // load data from attachment into jsonedit element identified and emptied earlier
        // metadata parsing from here:
        // https://www.geeksforgeeks.org/javascript/how-to-convert-map-to-json-in-javascript/
        
        fetch(attachment.href)
          .then(result => Arrow.tableFromIPC(result))
          .then(arrow_table => {
          
            let newed = new JSONEditor.JSONEditor({
              target: jse, 
              props: {
                content: {
                  json: [{
                    "geoarrow table": JSON.parse(JSON.stringify(arrow_table)),
                    "geoarrow metadata": JSON.parse(JSON.stringify(Object.fromEntries(arrow_table.schema.fields[3].metadata)))
                  }]
                }
              }
            });
            //debugger;
            console.log(arrow_table);

          });
  }'
)

onRender(wgt, js_code, data = list(name = "mydata"))

