package com.mob5.smarthouse.main_screen

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatButton
import androidx.recyclerview.widget.RecyclerView
import com.mob5.smarthouse.AddRoomScreen
import com.mob5.smarthouse.R
import com.mob5.smarthouse.common.MyRetrofit
import com.mob5.smarthouse.common.Rooms
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class HomeFragment : Fragment() {
    lateinit var rooms_rec: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_home, container, false)

        rooms_rec = root.findViewById(R.id.rooms_rec)

        val token = root.context.getSharedPreferences("data", Context.MODE_PRIVATE).getString("token", null)
        val call = MyRetrofit.getRetrofit().getRooms(token!!, "5FA1B987-3890-4A87-9712-ACDEAD0173AE")
        call.enqueue(object : Callback<Rooms>{
            override fun onResponse(call: Call<Rooms>, response: Response<Rooms>) {
                response.body()?.let { rooms_rec.adapter = RoomsAdapter(requireContext(), it) }
            }

            override fun onFailure(call: Call<Rooms>, t: Throwable) {
                AlertDialog.Builder(requireContext()).setTitle("Ошибка").setMessage(t.message).setPositiveButton("OK", null).show()
            }
        })

        root.findViewById<AppCompatButton>(R.id.add_room_btn).setOnClickListener{
            startActivity(Intent(requireContext(), AddRoomScreen::class.java))
        }
        // Inflate the layout for this fragment
        return root

    }

}