package com.example.modifier.ui.backup

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.modifier.Global
import com.example.modifier.R
import com.example.modifier.Utils
import com.example.modifier.adapter.BackupAdapter
import com.example.modifier.data.AppDatabase
import com.example.modifier.data.BackupItem
import com.example.modifier.data.BackupItemDao
import com.example.modifier.databinding.FragmentBackupBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class BackupFragment : Fragment() {
    private lateinit var binding: FragmentBackupBinding
    private val list = mutableListOf<BackupItem>()
    private lateinit var adapter: BackupAdapter
    private val backupItemDao: BackupItemDao by lazy {
        AppDatabase.getDatabase(requireContext()).itemDao()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        if (this::binding.isInitialized) {
            return binding.root
        }
        binding = FragmentBackupBinding.inflate(inflater, container, false)
        adapter = BackupAdapter(requireContext(), list, backupItemDao)
        binding.rvBackup.adapter = adapter
        binding.rvBackup.layoutManager = LinearLayoutManager(requireContext())
        binding.fabBackup.setOnClickListener {
            Utils.makeLoadingButton(requireContext(), binding.fabBackup)
            lifecycleScope.launch {
                withContext(Dispatchers.IO) {
                    val backup = Global.backup(backupItemDao, "manual", 0)
                    list.add(0, backup)
                }

                adapter.notifyItemInserted(0)
                binding.fabBackup.isEnabled = true
                binding.fabBackup.icon =
                    AppCompatResources.getDrawable(requireContext(), R.drawable.ic_add)
            }
        }
        binding.refresh.setOnRefreshListener {
            lifecycleScope.launch {
                withContext(Dispatchers.IO) {
                    refresh()
                }
            }
        }

        binding.lifecycleOwner = this
        viewLifecycleOwner.lifecycleScope.launch {
            // repeatOnLifecycle launches the block in a new coroutine every time the
            // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED.
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                withContext(Dispatchers.IO) {
                    refresh()
                }
            }
        }

        return binding.root
    }

    private suspend fun refresh() {
        val all = backupItemDao.getAll()
        list.clear()
        list.addAll(all)
        withContext(Dispatchers.Main) {
            adapter.notifyDataSetChanged()
        }
        binding.refresh.isRefreshing = false
    }

}
