package org.wntr.mdeditor

import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import org.wntr.mdeditor.MainActivity.Companion.credManager
import org.wntr.mdeditor.databinding.ActivityMetadataBinding

class MetadataActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMetadataBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMetadataBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.title.setText(metaData.get("title") ?: getDisplayName(applicationContext, thisFileUri))
        binding.url.setText(metaData.get("url"))
        binding.featureImage.setText(metaData.get("feature_image"))
        binding.author.setText(metaData.get("author") ?: credManager.username)
    }

    fun onButtonSaveClick(view: View) {
        Log.d(javaClass.simpleName, "Getting Metadata:\ntitle:\t${binding.title.text}\nfeature_image:\t${binding.featureImage.text}")
        metaData.put("title", binding.title.text.toString())
        metaData.put("feature_image", binding.featureImage.text.toString())
        if (binding.author.text.toString() != MainActivity.credManager.username) {
            var apiHost: String? = null
            if (metaData.get("url") !== null) {
                val url = Uri.parse(metaData.get("url"))
                apiHost = url.scheme + "://" + url.host
            } else apiHost = MainActivity.credManager.instance
            credManager.saveCredentialsToSharedPrefs(Credentials(apiHost, binding.author.text.toString()))
        }
        metaData.put("author", binding.author.text.toString())
        MainActivity.readOnResume = false
        finish()
    }
}