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 kotlinx.android.synthetic.main.comment_component.commentaryLayout
import kotlinx.android.synthetic.main.comment_component.commentaryText
import kotlinx.android.synthetic.main.comment_component.userImgCom
import kotlinx.android.synthetic.main.comment_component.view.commentaryBtn
import kotlinx.android.synthetic.main.comment_component.view.commentaryLayout
import kotlinx.android.synthetic.main.comment_component.view.commentaryText
import kotlinx.android.synthetic.main.comment_component.view.userImgCom
import kotlinx.android.synthetic.main.dialog_thread.view.materialToolbar
import kotlinx.android.synthetic.main.view_commentary.view.replyBtn
import kotlinx.android.synthetic.main.view_commentary.view.userCommentImg
import kotlinx.android.synthetic.main.view_commentary.view.userCommentary
import kotlinx.android.synthetic.main.view_commentary.view.userTxt
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.models.CommentaryModel

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

    // 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.
        val view = inflater.inflate(R.layout.dialog_thread, container, false)
        comment = arguments?.getSerializable("comment") as CommentaryModel

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

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

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

        view.materialToolbar.setTitle("Thread")
        view.materialToolbar.setNavigationIcon(R.drawable.baseline_arrow_back_24)
        view.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 = view?.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())
                    commentaryText.text?.clear()
                    this.getComments()
                } else {
                    ManagerSingleton.toast(getString(R.string.errorCommentaryMsg), requireActivity())
                }
            }
        }
    }
}
