/**
 * ProjectLaogai
 *
 * Copyright 2019  <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 com.afollestad.materialdialogs.MaterialDialog
import kotlinx.android.synthetic.main.fragment_home.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.mosad.seil0.projectlaogai.R
import org.mosad.seil0.projectlaogai.controller.CacheController.Companion.mensaMenu
import org.mosad.seil0.projectlaogai.controller.CacheController.Companion.timetables
import org.mosad.seil0.projectlaogai.hsoparser.DataTypes
import org.mosad.seil0.projectlaogai.hsoparser.Meal
import org.mosad.seil0.projectlaogai.hsoparser.NotRetardedCalendar
import org.mosad.seil0.projectlaogai.hsoparser.TimetableDay
import org.mosad.seil0.projectlaogai.uicomponents.DayCardView
import org.mosad.seil0.projectlaogai.uicomponents.LessonLinearLayout
import org.mosad.seil0.projectlaogai.uicomponents.MealLinearLayout
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 = "MyActivity"
    private val formatter = SimpleDateFormat("E dd.MM", Locale.getDefault())

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view: View = inflater.inflate(R.layout.fragment_home, container, false)

        addMensaMenu().get()
        addTimeTable().get()

        // Inflate the layout for this fragment
        return view
    }

    /**
     * add the current mensa meal to the home screens
     */
    private fun addMensaMenu() = doAsync {

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

        uiThread {

            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)))
                }

                linLayout_Home.addView(mensaCardView)
            }

        }

    }

    /**
     * add the current timetable to the home screen
     */
    private fun addTimeTable() = doAsync {
        val dayIndex = NotRetardedCalendar().getDayOfWeekIndex()
        val cal = Calendar.getInstance()
        var dayCardView: DayCardView

        uiThread {

            if (isAdded) {
                if (timetables.isNotEmpty() && dayIndex < 6) {

                    // first check the current day
                    dayCardView = addDayTimetable(timetables[0].timetable.days[dayIndex])
                    dayCardView.setDayHeading(resources.getString(R.string.today_date, formatter.format(cal.time)))

                    // if there are no lessons try to find the next day with a lesson
                    if (dayCardView.getLinLayoutDay().childCount <= 1)
                        dayCardView = findNextDay(0, dayIndex + 1)

                    linLayout_Home.addView(dayCardView)
                } else if (dayIndex == 6) {
                    // if that's the case it's sunday
                    dayCardView = findNextDay(1, 0)
                    linLayout_Home.addView(dayCardView)
                } else {
                    MaterialDialog(context!!)
                        .title(R.string.error)
                        .message(R.string.timetable_error)
                        .show()
                    Log.e(className, "could not load timetable") // TODO send feedback
                }
            }
        }

    }

    /**
     * add the timetable of one day to the home-screen
     * @param dayTimetable the day you wish to add
     */
    private fun addDayTimetable(dayTimetable: TimetableDay) : DayCardView{
        var helpLesson = LessonLinearLayout(context)
        val dayCardView = DayCardView(context!!)

        for ((tsIndex, timeslot) in dayTimetable.timeslots.withIndex()) {

            for(lesson in timeslot) {
                if(lesson.lessonSubject.isNotEmpty()) {

                    val lessonLayout = LessonLinearLayout(context)
                    lessonLayout.setLesson(lesson, DataTypes().getTime()[tsIndex])
                    dayCardView.getLinLayoutDay().addView(lessonLayout)

                    if (lesson != timeslot.last()) {
                        lessonLayout.disableDivider()
                    }

                    helpLesson = lessonLayout
                }
            }
        }

        helpLesson.disableDivider()

        return  dayCardView
    }

    /**
     * find the next day with a lesson
     * @param startWeekIndex the week you want to start searching
     * @param startDayIndex the day index you want to start searching
     * @return a DayCardView with all lessons added
     */
    private fun findNextDay(startWeekIndex: Int, startDayIndex: Int) : DayCardView {
        val cal = Calendar.getInstance()
        var dayCardView = DayCardView(context!!)
        var dayTimetable: TimetableDay? = null
        var dayIndexSearch = startDayIndex
        var weekIndexSearch = startWeekIndex

        loop@ while (dayTimetable == null && weekIndexSearch <= timetables.size) {
            for (i in (dayIndexSearch) ..5) {
                dayTimetable = timetables[weekIndexSearch].timetable.days[i]
                cal.add(Calendar.DATE, 1)

                // add the timetable to the card, if it contains at least one lesson break!
                dayCardView = addDayTimetable(dayTimetable)
                dayCardView.setDayHeading(formatter.format(cal.time))

                if (dayCardView.getLinLayoutDay().childCount > 1)
                    return dayCardView
            }
            dayIndexSearch = 0
            weekIndexSearch++
            cal.add(Calendar.DATE, 1)
        }

        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
    }

}
