package de.sebse.fuplanner2.ui.details

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.work.workDataOf
import de.sebse.fuplanner2.R
import de.sebse.fuplanner2.auth.AppAccounts
import de.sebse.fuplanner2.database.Lecturer
import de.sebse.fuplanner2.databinding.FragmentRefreshRecyclerBinding
import de.sebse.fuplanner2.utils.enqueueOneTimeWork
import de.sebse.fuplanner2.worker.AbstractAccountWorker.Companion.KEY_ACCOUNT_NAME
import de.sebse.fuplanner2.worker.AbstractAccountWorker.Companion.KEY_COURSE_ID
import de.sebse.fuplanner2.worker.CourseWorker


class DetailsFragment : Fragment() {

    private var title: String = ""
    private val args: DetailsFragmentArgs by navArgs()
    private val detailsViewModel: DetailsViewModel by viewModels { DetailsViewModelFactory(args.courseId) }
    private lateinit var navController: NavController
    private lateinit var binding: FragmentRefreshRecyclerBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val viewManager = LinearLayoutManager(context)
        val viewAdapter = DetailsAdapter(this::launchFragment, this::sendMail)
        return inflater.inflate(R.layout.fragment_refresh_recycler, container, false).apply {
            binding.recyclerView.apply {
                setHasFixedSize(true)

                layoutManager = viewManager
                adapter = viewAdapter
            }
            binding.swipeRefreshLayout.setOnRefreshListener {
                enqueueOneTimeWork<CourseWorker>(context.applicationContext) {
                    it.setInputData(workDataOf(
                        KEY_ACCOUNT_NAME to AppAccounts.getInstance().selectedAccount?.name,
                        KEY_COURSE_ID to args.courseId
                    ))
                }.observe(viewLifecycleOwner, Observer {
                    if (it.state.isFinished)
                        binding.swipeRefreshLayout.isRefreshing = false
                })
            }
            detailsViewModel.course.observe(viewLifecycleOwner, Observer {
                viewAdapter.lecturers = it.lecturers
                this@DetailsFragment.title = it.title
            })
            navController = findNavController()
        }
    }

    private fun sendMail(lecturer: Lecturer) {
        val intent = Intent(Intent.ACTION_SENDTO)
        intent.type = "text/html"
        intent.data = Uri.fromParts("mailto", lecturer.email, null)
        intent.putExtra(Intent.EXTRA_SUBJECT, this.title)
        intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.email_preview, lecturer.firstName, lecturer.lastName))
        startActivity(Intent.createChooser(intent, getString(R.string.send_email, lecturer.firstName, lecturer.lastName)))
    }

    private fun launchFragment(btnType: DetailsAdapter.ButtonTypes) {
        when (btnType) {
            DetailsAdapter.ButtonTypes.DESCRIPTION ->
                this.navController.navigate(DetailsFragmentDirections.actionCourseDetailsToDescriptionFragment(args.courseId, title))
            DetailsAdapter.ButtonTypes.RESOURCES -> TODO()
            DetailsAdapter.ButtonTypes.GRADEBOOK -> TODO()
            DetailsAdapter.ButtonTypes.ANNOUNCEMENTS ->
                this.navController.navigate(DetailsFragmentDirections.actionCourseDetailsToCourseAnnouncements(args.courseId, title))
            DetailsAdapter.ButtonTypes.ASSIGNMENTS -> TODO()
            DetailsAdapter.ButtonTypes.EVENTS ->
                this.navController.navigate(DetailsFragmentDirections.actionCourseDetailsToCourseEvents(args.courseId, title))
        }
    }
}
