package org.libre.agosto.p2play.dialogs

import android.app.Dialog
import android.os.AsyncTask
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import org.libre.agosto.p2play.ManagerSingleton
import org.libre.agosto.p2play.R
import org.libre.agosto.p2play.adapters.CommentariesAdapter
import org.libre.agosto.p2play.ajax.Comments
import org.libre.agosto.p2play.databinding.DialogThreadBinding
import org.libre.agosto.p2play.models.CommentaryModel

class ThreadDialog : DialogFragment() {
    private lateinit var comment: CommentaryModel
    lateinit var fragmentManager2: FragmentManager
    private val client: Comments = Comments()

    private var _binding: DialogThreadBinding? = null
    // This property is only valid between onCreateView and
// onDestroyView.
    private val binding get() = _binding!!


    // The system calls this to get the DialogFragment's layout, regardless of
    // whether it's being displayed as a dialog or an embedded fragment.
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        // Inflate the layout to use as a dialog or embedded fragment.
        _binding = DialogThreadBinding.inflate(inflater, container, false)
        val view = binding.root
        comment = arguments?.getSerializable("comment") as CommentaryModel

        binding.commentThread?.userTxt?.text = comment.username
        binding.commentThread?.userCommentary?.text = comment.commentary
        Picasso.get().load("https://${ManagerSingleton.url}${comment.userImageUrl}").into(binding.commentThread?.userCommentImg)
        binding.commentThread?.replyBtn?.visibility = View.GONE

        if (ManagerSingleton.user.status == 1) {
            binding.commentBox?.commentaryText?.setText("${comment.nameChannel}@${comment.userHost} ")
            if (ManagerSingleton.user.avatar != "") {
                Picasso.get().load("https://${ManagerSingleton.url}${ManagerSingleton.user.avatar}").into(binding.commentBox?.userImgCom)
            }

            binding.commentBox?.commentaryText?.requestFocus()
            binding.commentBox?.commentaryBtn?.setOnClickListener { this.replyThread() }
        } else {
            binding.commentBox?.commentaryLayout?.visibility = View.GONE
        }

        binding.materialToolbar.setTitle("Thread")
        binding.materialToolbar.setNavigationIcon(R.drawable.baseline_arrow_back_24)
        binding.materialToolbar.setNavigationOnClickListener {
            dismiss()
            this.fragmentManager2.popBackStack()
        }

        this.getComments()

        return view
    }

    // The system calls this only when creating the layout in a dialog.
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        return dialog
    }

    private fun getComments() {
        AsyncTask.execute {
            val data =
                this.client.getCommentariesThread(this.comment.videoId, this.comment.id)
            activity?.runOnUiThread {
                this.setDataComments(data)
            }
        }
    }

    private fun setDataComments(data: ArrayList<CommentaryModel>) {
        // Set data for RecyclerView
        val viewAdapter = CommentariesAdapter(data).setFragmentManager(this.fragmentManager2)

        view?.findViewById<RecyclerView>(R.id.listCommentaries)?.let {
            // use this setting to improve performance if you know that changes
            // in content do not change the layout size of the RecyclerView
            it.setHasFixedSize(true)
            // use a linear layout manager
            it.layoutManager = LinearLayoutManager(activity)

            // specify an viewAdapter (see also next example)
            it.adapter = viewAdapter
        }
    }

    private fun replyThread() {
        val commentary = binding.commentBox?.commentaryText?.text.toString()

        if (commentary == "") {
            ManagerSingleton.toast(getString(R.string.emptyCommentaryMsg), requireActivity())
            return
        }

        AsyncTask.execute {
            val res = this.client.replyThread(ManagerSingleton.token.token, this.comment.videoId, this.comment.id, commentary)
            activity?.runOnUiThread {
                if (res) {
                    ManagerSingleton.toast(getString(R.string.makedCommentaryMsg), requireActivity())
                    binding.commentBox?.commentaryText?.text?.clear()
                    this.getComments()
                } else {
                    ManagerSingleton.toast(getString(R.string.errorCommentaryMsg), requireActivity())
                }
            }
        }
    }
}
