package it.danieleverducci.openweddingapp.ui.table

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.FragmentTableBinding
import it.danieleverducci.openweddingapp.entities.Table
import it.danieleverducci.openweddingapp.networking.AuthenticatedItemNet
import it.danieleverducci.openweddingapp.networking.TableNet

class TableFragment: Fragment() {
    companion object {
        val TAG = "TableFragment"
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentTableBinding.inflate(inflater, container, false)
        val user = (activity?.application as DeRApplication).token?.user

        // Check if user can see this page
        if ((activity!!.application as DeRApplication).remoteSettings.showTableEnabled) {

            // User can see page
            binding.tableTitle.text =
                getString(R.string.table_title).format(user?.name, user?.surname)
            binding.tableName.text = user?.table

            // Load data
            val tn = TableNet(requireContext(), (activity!!.application as DeRApplication).token!!.token)
            tn.getItem(object : AuthenticatedItemNet.OnItemObtainedListener<Table> {
                override fun OnItemObtained(item: Table) {
                    // Re-set table just to be sure (may have changed after the user log in)
                    binding.tableName.text = item.table
                    binding.tablePeople.visibility = View.VISIBLE
                    binding.tablePeople.text =
                        "${getString(R.string.table_footer)} ${item.getPeoplePrintableList()}"
                }

                override fun OnError(error: VolleyError) {
                    Log.e(TAG, error.toString())
                }
            })
        } else {
            // User can't see page
            binding.tableTitle.text = getString(R.string.table_title_disabled)
            binding.tableName.visibility = View.GONE
            binding.tablePeople.visibility = View.GONE
        }
        return binding.root
    }

}