package it.danieleverducci.openweddingapp.ui.presence

import android.animation.LayoutTransition
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.android.volley.VolleyError
import it.danieleverducci.openweddingapp.DeRApplication
import it.danieleverducci.openweddingapp.R
import it.danieleverducci.openweddingapp.databinding.FragmentPresenceBinding
import it.danieleverducci.openweddingapp.entities.Like
import it.danieleverducci.openweddingapp.entities.Presence
import it.danieleverducci.openweddingapp.networking.AuthenticatedItemNet
import it.danieleverducci.openweddingapp.networking.LikeNet
import it.danieleverducci.openweddingapp.networking.PresenceNet
import it.danieleverducci.openweddingapp.ui.gallery.GalleryFragment
import it.danieleverducci.openweddingapp.utils.SharedPreferencesManager

class PresenceFragment : Fragment() {
    companion object {
        private val TAG = "PresenceFragment"
    }
    private lateinit var binding: FragmentPresenceBinding
    private lateinit var presenceNet: PresenceNet
    private var presenceToggleStatus: Boolean? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        presenceNet = PresenceNet(requireContext(), (activity!!.application as DeRApplication).token!!.token)
        binding = FragmentPresenceBinding.inflate(inflater, container, false)

        // Enable animations for buttons size change
        binding.presenceButtonsContainer.getLayoutTransition()
            .enableTransitionType(LayoutTransition.CHANGING);

        // Hide buttons if user responded
        val savedPresence = SharedPreferencesManager.loadPresence(requireContext())
        showPresence(savedPresence)

        if (savedPresence == null) {
            // Check also presence online in case it differs (same user with multiple devices)
            binding.progress.visibility = View.VISIBLE
            presenceNet.getList(object : AuthenticatedItemNet.OnItemListObtainedListener<Presence> {
                override fun OnItemListObtained(
                    items: ArrayList<Presence>?,
                    page: Int,
                    more: Boolean
                ) {
                    binding.progress.visibility = View.GONE
                    if (items != null && items.size > 0) {
                        val presenceFromNet = items.get(0)
                        SharedPreferencesManager.savePresence(requireContext(), presenceFromNet)
                        showPresence(presenceFromNet)
                    } else {
                        showPresence(null)
                    }
                }

                override fun OnError(error: VolleyError) {
                    binding.progress.visibility = View.GONE
                    Log.e(TAG, "Unable to obtain user presence answer")
                }

            })
        }

        binding.presenceSumbit.setOnClickListener {
            val presence = Presence(this.presenceToggleStatus!!, binding.presenceNotes.text.toString())
            sendPresence(presence)
        }

        binding.presenceYes.setOnClickListener {
            onPresenceButtonClicked(true)
        }

        binding.presenceNo.setOnClickListener {
            onPresenceButtonClicked(false)
        }

        return binding.getRoot()
    }

    private fun onPresenceButtonClicked(present: Boolean) {
        // Colors
        binding.presenceYes.setBackgroundResource(
            if(present) R.drawable.button_background else R.drawable.button_background_secondary
        )
        binding.presenceNo.setBackgroundResource(
            if(present) R.drawable.button_background_secondary else R.drawable.button_background
        )
        // Dimension
        binding.presenceYes.layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, if(present) 2.0f else 1.0f)
        binding.presenceNo.layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, if(present) 1.0f else 2.0f)
        // Notes text box
        binding.presenceNotes.visibility = if(present) View.VISIBLE else View.GONE
        // Value
        this.presenceToggleStatus = present
        binding.presenceAnswerAnswering.visibility = View.VISIBLE
    }

    private fun sendPresence(p: Presence) {
        binding.progress.visibility = View.VISIBLE
        presenceNet.postItem(
            object : AuthenticatedItemNet.OnItemPostedListener<Presence> {
                override fun OnItemPosted(rp: Presence) {
                    binding.progress.visibility = View.GONE
                    SharedPreferencesManager.savePresence(requireContext(), rp)
                    showPresence(rp)
                }

                override fun OnError(error: VolleyError) {
                    binding.progress.visibility = View.GONE
                    Log.e(TAG, error.message ?: "")
                    Toast.makeText(context, R.string.presence_error, Toast.LENGTH_SHORT)
                        .show()
                }
            },
            p
        )
    }

    /**
     * Shows/hides presence buttons and text
     */
    private fun showPresence(p: Presence?) {
        if (p == null) {
            binding.presenceAnswerUnanswered.visibility = View.VISIBLE
            binding.presenceAnswerAnsweredYes.visibility = View.GONE
            binding.presenceAnswerAnsweredNo.visibility = View.GONE
            return
        }

        binding.presenceAnswerUnanswered.visibility = View.GONE
        binding.presenceAnswerAnsweredYes.visibility = if (p.willBePresent) View.VISIBLE else View.GONE
        binding.presenceAnswerAnsweredNo.visibility = if (p.willBePresent) View.GONE else View.VISIBLE
        binding.presenceNotes.visibility = View.GONE
    }
}