/**
 * 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.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import kotlinx.coroutines.*
import org.mosad.seil0.projectlaogai.R
import org.mosad.seil0.projectlaogai.controller.cache.CacheController.Companion.mensaMenu
import org.mosad.seil0.projectlaogai.controller.cache.TimetableController
import org.mosad.seil0.projectlaogai.databinding.FragmentHomeBinding
import org.mosad.seil0.projectlaogai.util.Meal
import org.mosad.seil0.projectlaogai.util.TimetableDay
import org.mosad.seil0.projectlaogai.uicomponents.DayCardView
import org.mosad.seil0.projectlaogai.uicomponents.MealLinearLayout
import org.mosad.seil0.projectlaogai.util.NotRetardedCalendar
import java.text.SimpleDateFormat
import java.util.*

/**
 * The "home" controller class
 * contains all needed parts to display the apps home screen
 */
class HomeFragment : Fragment() {

    private val className = "HomeFragment"
    private val formatter = SimpleDateFormat("E dd.MM", Locale.getDefault())
    private lateinit var binding: FragmentHomeBinding

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

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

        addMensaMenu()
        addTimeTable()
    }

    /**
     * add the current mensa meal to the home screens
     */
    private fun addMensaMenu() = GlobalScope.launch(Dispatchers.Default) {

        var dayMeals: ArrayList<Meal>
        val cal = Calendar.getInstance()
        val mensaCardView = DayCardView(context!!)

        withContext(Dispatchers.Main) {

            if (isAdded) {
                if (cal.get(Calendar.HOUR_OF_DAY) < 15) {
                    dayMeals = mensaMenu.currentWeek.days[NotRetardedCalendar.getDayOfWeekIndex()].meals
                    mensaCardView.setDayHeading(activity!!.resources.getString(R.string.today_date, formatter.format(cal.time)))
                } else {
                    dayMeals = mensaMenu.currentWeek.days[NotRetardedCalendar.getTomorrowWeekIndex()].meals
                    cal.add(Calendar.DATE, 1)
                    mensaCardView.setDayHeading(activity!!.resources.getString(R.string.tomorrow_date, formatter.format(cal.time)))
                }

                if (dayMeals.size >= 2) {
                    // get the index of the first meal, not a "Schneller Teller"
                    loop@ for ((i, meal) in dayMeals.withIndex()) {
                        if (meal.heading.contains("Essen")) {

                            val meal1Layout = MealLinearLayout(context)
                            meal1Layout.setMeal(dayMeals[i])
                            mensaCardView.getLinLayoutDay().addView(meal1Layout)

                            val meal2Layout = MealLinearLayout(context)
                            meal2Layout.setMeal(dayMeals[i + 1])
                            meal2Layout.disableDivider()
                            mensaCardView.getLinLayoutDay().addView(meal2Layout)

                            break@loop
                        }
                    }

                } else {
                    mensaCardView.getLinLayoutDay().addView(getNoCard(resources.getString(R.string.mensa_closed)))
                }

                binding.linLayoutHome.addView(mensaCardView)
            }

        }

    }

    /**
     * add the current timetable to the home screen
     */
    private fun addTimeTable() = GlobalScope.launch(Dispatchers.Default) {

        withContext(Dispatchers.Main) {

            if (isAdded && TimetableController.timetable.isNotEmpty()) {
                try {
                    val dayCardView = findNextDay(NotRetardedCalendar.getDayOfWeekIndex())
                    binding.linLayoutHome.addView(dayCardView)
                } catch (ex: Exception) {
                    Log.e(className, "could not load timetable", ex) // TODO send feedback
                }
            }
        }

    }

    /**
     * find the next day with a lesson
     * start at week 0, startDayIndex and search every cached week until we find a) a day with a timetable
     * or b) we find no timetable and add a no lesson card
     * @param startDayIndex the day index you want to start searching
     * @return a DayCardView with all lessons added
     */
    private fun findNextDay(startDayIndex: Int): DayCardView {
        val dayCardView = DayCardView(context!!)
        var dayTimetable: TimetableDay? = null
        var dayIndexSearch = startDayIndex
        var weekIndexSearch = 0

        while (dayTimetable == null && weekIndexSearch < TimetableController.timetable.size) {
            for (dayIndex in dayIndexSearch..5) {
                dayTimetable = TimetableController.timetable[weekIndexSearch].days[dayIndex]

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

                // if there are no lessons don't show the dayCardView
                if (dayCardView.getLinLayoutDay().childCount > 1)
                    return dayCardView
            }

            weekIndexSearch++
            dayIndexSearch = 0
        }

        // there was no day found in the cached weeks, add no lesson card
        dayCardView.setDayHeading(formatter.format(Calendar.getInstance().time))
        dayCardView.getLinLayoutDay().addView(getNoCard(resources.getString(R.string.no_lesson_today))) // if there is no lecture at all show the no lesson card
        return dayCardView
    }

    /**
     * @param text the text to show on the card
     * @return a TextView with the text and all needed parameters
     */
    private fun getNoCard(text: String): TextView {
        val noLesson = TextView(context)
        noLesson.text = text
        noLesson.textSize = 18.0F
        noLesson.setTypeface(null, Typeface.BOLD)
        noLesson.textAlignment = View.TEXT_ALIGNMENT_CENTER
        noLesson.setPadding(7, 7, 7, 7)

        return noLesson
    }

}
