package org.wntr.mdeditor

import android.util.Log
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.KotlinModule
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject

class mdMeta {
    var metaData = mutableMapOf<String,String>()
    var ID: String? = null
    var updatedAt: String? = null
    var cursor: String =  "{ line: 0, ch: 0, sticky: null }"
        get() =
            if (field.equals("null"))  "{ line: 0, ch: 0, sticky: null }"
            else field

    fun put(key: String, value: String) {
        metaData.put(key, value)
    }
    fun get(key: String): String?{
        return metaData.get(key)
    }

    override fun toString(): String {
        if (metaData.size == 0) return ""
        var metaString = "---\n"
        for (key in metaData.keys) {
            if (metaData.get(key) != null) metaString += "$key: ${metaData.get(key)}\n"
        }
        metaString += "---\n"
        return metaString
    }


    fun extractMetadataFromMarkdown(markdown: String) : String {
        val charactersBetweenGroupedHyphens = Regex("^---([\\s\\S]*?)---\n")
        val metadataMatched = charactersBetweenGroupedHyphens.find(markdown)
        ID = null

        if (metadataMatched == null || metadataMatched.value == "---\n---\n") {
            Log.d(javaClass.simpleName,"No metadata included")
            metaData = mutableMapOf()
            return markdown
        }
        val metadata = metadataMatched.value

        val mapper = ObjectMapper(YAMLFactory())
        mapper.registerModule(KotlinModule())
        metaData = mapper.readValue(metadata, Map::class.java) as MutableMap<String,String>
        for (entry in metaData) {
            Log.d(javaClass.simpleName,"${entry.key}: ${entry.value}")
        }
        return markdown.substring(metadata.length)
    }

    fun getId(): String? {
        if (ID !== null)
            return ID as String
        if (metaData.get("url") == "") return null

        try {
            val response = MainActivity.api.postApi.getPosts().execute()

            Log.d(javaClass.simpleName, "result: ${response.code()}")
            if (response.isSuccessful) {
                val resp = JSONObject(response.body()!!.string())
                val posts = resp.getJSONArray("posts")
                var remoteDoc : JSONObject? =  null

                for (i in 0 until posts.length()) {
                    remoteDoc = posts.getJSONObject(i)
                    if (remoteDoc.getString("url") == metaData.get("url")) break
                }

                if (remoteDoc == null ){
                    Log.d(javaClass.simpleName, "Could not find post ID ${metaData.get("url")}. Already deleted?")
                    metaData.put("url", "")
                    ID = null
                    return ID
                }
                ID = remoteDoc.getString("id")
                updatedAt = remoteDoc.getString("updated_at")
                Log.d(javaClass.simpleName, "Document is online at ${
                    metaData.get("url")}\nID: ${ID}")
                return ID
            } else {
                return null
            }
        } catch(e: Exception) {
            Log.d(javaClass.simpleName, "Couldn't get post list: $e")
            return null
        }
    }
}