package com.xd.roomdatabasekotlin

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import java.util.*
import kotlin.collections.ArrayList
import kotlin.random.Random.Default.nextInt


class MyListFragment : Fragment() {
    private val comments = arrayOf(
        "Canada", "SFU", "CMPT362",
        "is", "is", "the", "best", "coolest", "place", "in", "the", "universe!"
    )
    private lateinit var addButton: Button
    private lateinit var deleteButton: Button
    private lateinit var deleteAllButton: Button
    private lateinit var myListView: ListView

    private lateinit var arrayList: ArrayList<Comment>
    private lateinit var arrayAdapter: MyListAdapter

    private lateinit var database: CommentDatabase
    private lateinit var databaseDao: CommentDatabaseDao
    private lateinit var repository: CommentRepository
    private lateinit var viewModelFactory: CommentViewModelFactory
    private lateinit var commentViewModel: CommentViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_my_list, container, false)
        myListView = view.findViewById(R.id.list)
        addButton = view.findViewById(R.id.add)
        deleteButton = view.findViewById(R.id.delete)
        deleteAllButton = view.findViewById(R.id.deleteall)

        arrayList = ArrayList()
        arrayAdapter = MyListAdapter(requireActivity(), arrayList)
        myListView.adapter = arrayAdapter

//        val application = requireNotNull(activity).application
        database = CommentDatabase.getInstance(requireActivity())
        databaseDao = database.commentDatabaseDao
        repository = CommentRepository(databaseDao)
        viewModelFactory = CommentViewModelFactory(repository)
        commentViewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(CommentViewModel::class.java)

        commentViewModel.allCommentsLiveData.observe(requireActivity(), Observer { it ->
            arrayAdapter.replace(it)
            arrayAdapter.notifyDataSetChanged()
        })

        addButton.setOnClickListener(){
            val index = (0..comments.size-1).random()
            val comment = Comment()
            comment.comment = comments[index]
            commentViewModel.insert(comment)
        }

        deleteButton.setOnClickListener(){
            commentViewModel.deleteFirst()
        }

        deleteAllButton.setOnClickListener(){
            commentViewModel.deleteAll()
        }

        return view
    }


}