/**
 * ProjectLaogai
 *
 * Copyright 2019-2020  <seil0@mosad.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

package org.mosad.seil0.projectlaogai.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.coroutines.*
import org.mosad.seil0.projectlaogai.R
import org.mosad.seil0.projectlaogai.controller.cache.TimetableController
import org.mosad.seil0.projectlaogai.controller.cache.TimetableController.timetable
import org.mosad.seil0.projectlaogai.controller.preferences.Preferences
import org.mosad.seil0.projectlaogai.databinding.FragmentTimetableBinding
import org.mosad.seil0.projectlaogai.uicomponents.dialogs.AddSubjectDialog
import org.mosad.seil0.projectlaogai.uicomponents.DayCardView
import org.mosad.seil0.projectlaogai.uicomponents.TextViewInfo
import org.mosad.seil0.projectlaogai.util.NotRetardedCalendar

/**
 * The timetable controller class
 * contains all needed parts to display and the timetable detail screen
 */
class TimetableFragment : Fragment() {

    private lateinit var binding: FragmentTimetableBinding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = FragmentTimetableBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.refreshLayoutTimetable.setProgressBackgroundColorSchemeColor(Preferences.themeSecondary)

        initActions() // init actions

        if (timetable.size > 1 && timetable[0].days.isNotEmpty() && timetable[1].days.isNotEmpty()) {
            initTimetable()
        } else {
            val txtViewInfo = TextViewInfo(context!!).set {
                txt = resources.getString(R.string.timetable_generic_error)
            }.showImage()
            binding.linLayoutTimetable.addView(txtViewInfo)
        }
    }

    /**
     * initialize the actions
     */
    private fun initActions() {

        binding.refreshLayoutTimetable.setOnRefreshListener {
            runBlocking { TimetableController.update(context!!).joinAll() }
            reloadTimetableUI()
        }

        // show the AddLessonDialog if the ftaBtn is clicked
        binding.faBtnAddSubject.setOnClickListener {
            AddSubjectDialog(context!!)
                .positiveButton {
                    TimetableController.addSubject(selectedCourse, selectedSubject, context)
                    runBlocking { reloadTimetableUI() }
                }.show()
        }

        // hide the btnCardValue if the user is scrolling down
        binding.scrollViewTimetable.setOnScrollChangeListener { _, _, scrollY, _, oldScrollY ->
            if (scrollY > oldScrollY) {
                binding.faBtnAddSubject.hide()
            } else {
                binding.faBtnAddSubject.show()
            }
        }

    }

    /**
     * add the current and next weeks lessons
     */
    private fun initTimetable() = GlobalScope.launch(Dispatchers.Default) {
        val currentDayIndex = NotRetardedCalendar.getDayOfWeekIndex()

        addTimetableWeek(currentDayIndex, 5, 0).join() // add current week
        addTimetableWeek(0, currentDayIndex - 1, 1) // add next week
    }

    private fun addTimetableWeek(dayBegin: Int, dayEnd: Int, week: Int) = GlobalScope.launch(Dispatchers.Main) {
        for (dayIndex in dayBegin..dayEnd) {
            val dayCardView = DayCardView(context!!)

            // some wired calendar magic, calculate the correct date to be shown
            // ((timetable week - current week * 7) + (dayIndex - dayIndex of current week)
            val daysToAdd = ((timetable[week].weekNumberYear - NotRetardedCalendar.getWeekOfYear())
                * 7 + (dayIndex - NotRetardedCalendar.getDayOfWeekIndex()))
            dayCardView.addTimetableDay(timetable[week].days[dayIndex], daysToAdd)

            // if there are no lessons don't show the dayCardView
            if (dayCardView.getLinLayoutDay().childCount > 1)
                binding.linLayoutTimetable.addView(dayCardView)

        }
    }

    /**
     * clear linLayout_Timetable, add the updated timetable
     */
    private fun reloadTimetableUI() = GlobalScope.launch(Dispatchers.Default) {
        withContext(Dispatchers.Main) {
            // remove all lessons from the layout
            binding.linLayoutTimetable.removeAllViews()

            // add the refreshed timetables
            val dayIndex = NotRetardedCalendar.getDayOfWeekIndex()

            addTimetableWeek(dayIndex, 5, 0).join() // add current week
            addTimetableWeek(0, dayIndex - 1, 1) // add next week

            binding.refreshLayoutTimetable.isRefreshing = false
        }
    }

}
