/**
 * 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.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ScrollView
import androidx.fragment.app.Fragment
import com.afollestad.materialdialogs.MaterialDialog
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.android.synthetic.main.fragment_timetable.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.mosad.seil0.projectlaogai.R
import org.mosad.seil0.projectlaogai.controller.CacheController
import org.mosad.seil0.projectlaogai.controller.CacheController.Companion.timetables
import org.mosad.seil0.projectlaogai.controller.PreferencesController.Companion.cCourse
import org.mosad.seil0.projectlaogai.controller.TCoRAPIController
import org.mosad.seil0.projectlaogai.hsoparser.DataTypes
import org.mosad.seil0.projectlaogai.hsoparser.NotRetardedCalendar
import org.mosad.seil0.projectlaogai.hsoparser.TimetableWeek
import org.mosad.seil0.projectlaogai.uicomponents.DayCardView
import org.mosad.seil0.projectlaogai.uicomponents.LessonLinearLayout
import java.text.SimpleDateFormat
import java.util.*

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

    private val formatter = SimpleDateFormat("E dd.MM", Locale.getDefault())
    private lateinit var scrollViewTimetable: ScrollView
    private lateinit var faBtnAddLesson: FloatingActionButton

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

        val view: View = inflater.inflate(R.layout.fragment_timetable, container, false)
        scrollViewTimetable = view.findViewById(R.id.scrollView_Timetable)
        faBtnAddLesson = view.findViewById(R.id.faBtnAddLesson)

        // init actions
        initActions()

        if (timetables[0].timetable.days.isNotEmpty() && timetables[1].timetable.days.isNotEmpty()) {
            addInitWeeks()
        } else {
            MaterialDialog(context!!)
                .title(R.string.error)
                .message(R.string.timetable_error)
                .show()
        }

        return view
    }

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

        uiThread {
            refreshLayout_Timetable.setOnRefreshListener {
                updateTimetableScreen()
            }

            faBtnAddLesson.setOnClickListener {
                MaterialDialog(context!!)
                    .title(text = "Vorlesung hinzufügen")
                    .message(text = "wähle einen Studiengang aus:\n\nWähle eine Vorlesung aus: \n\n Diese Funktion ist noch nicht verfügbar")
                    .show()
            }

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

        }

    }

    /**
     * add the current and next weeks lessons
     */
    private fun addInitWeeks() = doAsync {
        val dayIndex = NotRetardedCalendar().getDayOfWeekIndex()
        val calendar = Calendar.getInstance()

        // add current week
        addWeek(dayIndex, 5, timetables[0].timetable, calendar).get()

        // add next week
        addWeek(0, dayIndex - 1, timetables[1].timetable, calendar)
    }

    private fun addWeek(dayStart: Int, dayEnd: Int, timetable: TimetableWeek, calendar: Calendar) = doAsync {
        uiThread {

            for (day in dayStart..dayEnd) {
                var helpLesson = LessonLinearLayout(context)
                val dayCardView = DayCardView(context!!)
                dayCardView.setDayHeading(formatter.format(calendar.time))

                // for each timeslot of the day
                for ((tsIndex, timeslot) in timetable.days[day].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()
                calendar.add(Calendar.DATE, 1)

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

            }

            calendar.add(Calendar.DATE, 1) // before this we are at a sunday (no lecture on sundays!)
        }
    }

    private fun updateTimetableScreen() = doAsync {
        // update the cache
        TCoRAPIController.getTimetable(cCourse.courseName, 0, context!!).get() // blocking since we want the new data
        TCoRAPIController.getTimetable(cCourse.courseName, 1, context!!).get() // blocking since we want the new data

        CacheController.readTimetable(cCourse.courseName, 0, context!!)
        CacheController.readTimetable(cCourse.courseName, 1, context!!)

        uiThread {
            // remove all menus from the layout
            linLayout_Timetable.removeAllViews()

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

            // add current week
            addWeek(dayIndex, 5, timetables[0].timetable, calendar).get()

            // add next week
            addWeek(0, dayIndex - 1, timetables[1].timetable, calendar)

            refreshLayout_Timetable.isRefreshing = false
        }
    }

}
