import std/[asyncdispatch, httpclient]
import std/json
import std/options
import std/strformat
import jester

# type
#   joplin_notebooks* = object
#     id: seq[string]
#     parent_id: seq[string]
#     title: seq[string]


# proc get_joplin_notebooks*(): Future[joplin_notebooks] {.async.} =
#   var j_nb: joplin_notebooks
#   var count = 0
#   var client = newAsyncHttpClient()
#   var json = await client.getContent("http://localhost:41184/folders?token=e5f6644fbf6a97ddc55648dae72b11caecda6c6642d8ce0d3b20129b89b196385737eb908923542c3343649ebbf865b55bda031ab4c3a16edc7723ef2ad77d8f")

#   let joplin_notebooks_Json = parseJson(json)
    
#   for nb in joplin_notebooks_Json["items"]:
#     j_nb.id.add(nb["id"].getstr) 
#     j_nb.parent_id.add(nb["parent_id"].getstr)
#     j_nb.title.add(nb["title"].getstr) 
#     count += 1

#   echo joplin_notebooks_Json["has_more"]

#   return j_nb


# Setup user data
type
  joplin_notebooks* = object    
    id*, parent_id*, title*: seq[string]
    req*: Request

proc get_joplin_notebooks*(token:string): Future[joplin_notebooks] {.async.} =
  
  # Variables
  var j_nb: joplin_notebooks
  var has_more: bool = true
  var page: int = 1
  var url: string
  var client = newAsyncHttpClient()
  
  # make sure to check all pages 
  while has_more == true:
    
    # request joplin API for notebooks
    url = fmt"http://localhost:41184/folders?page={page}&token={token}"
    var json = await client.getContent(url)

    # parse jason
    let joplin_notebooks_Json = parseJson(json)

    # valider qu'il n'y a plus de page 
    if not joplin_notebooks_Json["has_more"].getBool:
      has_more = false 
    
    # store json info into an object
    var count: int = 1
    for nb in joplin_notebooks_Json["items"]:
      j_nb.id.add(nb["id"].getstr)
      j_nb.parent_id.add(nb["parent_id"].getstr)
      j_nb.title.add(nb["title"].getstr)
      count += 1
    
    # aller à la page suivante
    page += 1    

  return j_nb


# var all_notebooks = "" 
var nb: joplin_notebooks
nb = waitFor get_joplin_notebooks("e5f6644fbf6a97ddc55648dae72b11caecda6c6642d8ce0d3b20129b89b196385737eb908923542c3343649ebbf865b55bda031ab4c3a16edc7723ef2ad77d8f")
# echo nb.title[1]

for i in nb.title:
  echo i

echo nb.title