#!/usr/bin/lua

-- Dependencies
local json = require ("dkjson")

-- Helper functions
-- String subtitution Helper
function interp(s, tab)
  return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
end

function get_title (text)
    j=string.find(text, "\n")
    if j==nil or j>55 then
        line1=text:sub(0, 55)
    else
        line1=text:sub(0, j-1)
        line1=line1:gsub(":", "")
    end
    return line1
end

function find_dreams(text)
    if string.find(text, "A dream") or string.find(text, "#dreamjournal") then
        return '"sueños",'
    else
        return ""
    end
end

function compose_text (fecha, text)

    j=string.find(text, "\n")
    if j==nil or j>55 then
        texto=text
    else
        line1=text:sub(0, j)
        texto=text:gsub(line1, "")
    end
    
    getmetatable("").__mod = interp
    post = [[
---
title: ${title}
date: ${date}
author: "Lumin"
tags: [
    "imported",
    "old blog",
    "write.as", ${dreams}
]
---

${body}
]] % {title = get_title(text), date = fecha, body = texto, dreams = find_dreams(text)}
    --print(post)
    return post
    
    --print(c.."---------"..line1)
    --c=c+1
end
-------------------------------------------------------
-- JSON decode & Markdown encode
-------------------------------------------------------
local f = io.open("posts.json", "r")
local content = f:read("*all")
f:close()

local obj, pos, err = json.decode (content, 1, nil)
if err then
  print ("Error:", err)
else
  print ("Author: ", obj.username)
  print ("collections_table", obj.collections)
    for i = 1,#obj.collections do
        local total_de_posts = obj.collections[i].total_posts
        print ("Total posts: ", total_de_posts)
        for j = 1, total_de_posts, 1 do
            local date = obj.collections[i].posts[j].updated
            local title = obj.collections[i].posts[j].slug
            local text = obj.collections[i].posts[j].body
            
            --print (j, "Time: ", obj.collections[i].posts[j].updated) -- Time is well set
            --print (j, "Titulo: ", obj.collections[i].posts[j].slug) -- needs parsing
            --print (j, "Texto: ", obj.collections[i].posts[j].body) -- Raw and good -- needs tag parsing

            -- We need to compose the string/file now properly and that's it. That is all in archivo.
            
            -- Set YALM
            -- 
            local archivo = date .. "\n" .. text
            local filename = "content/blog/cyberespacio/".. title .. ".md"
                        
            local filewrite = assert(io.open(filename, "w"))
            filewrite:write(compose_text (date, text))
            filewrite:close()
        end
    end
end
