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

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

# 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

proc get_joplin_tags*(): Future[joplin_tags] {.async.} =
    var j_tags: joplin_tags
    var count = 0
    var client = newAsyncHttpClient()
    var json = await client.getContent("http://localhost:41184/tags?token=e5f6644fbf6a97ddc55648dae72b11caecda6c6642d8ce0d3b20129b89b196385737eb908923542c3343649ebbf865b55bda031ab4c3a16edc7723ef2ad77d8f")

    let joplin_tags_Json = parseJson(json)
    
    for tag in joplin_tags_Json["items"]:
      j_tags.id.add(tag["id"].getstr) 
      j_tags.parent_id.add(tag["parent_id"].getstr)
      j_tags.title.add(tag["title"].getstr) 
      count += 1
    return j_tags