/**
 * 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.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.mosad.seil0.projectlaogai.R
import org.mosad.seil0.projectlaogai.controller.cache.CacheController
import org.mosad.seil0.projectlaogai.controller.cache.CacheController.Companion.mensaMenu
import org.mosad.seil0.projectlaogai.controller.preferences.Preferences
import org.mosad.seil0.projectlaogai.databinding.FragmentMensaBinding
import org.mosad.seil0.projectlaogai.uicomponents.DayCardView
import org.mosad.seil0.projectlaogai.uicomponents.MealLinearLayout
import org.mosad.seil0.projectlaogai.uicomponents.TextViewInfo
import org.mosad.seil0.projectlaogai.util.MensaWeek
import org.mosad.seil0.projectlaogai.util.NotRetardedCalendar

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

    private lateinit var binding: FragmentMensaBinding

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

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

        binding.refreshLayoutMensa.setProgressBackgroundColorSchemeColor(Preferences.themeSecondary)

        initActions() // init actions

        GlobalScope.launch(Dispatchers.Default) {
            val dayCurrent =  if(NotRetardedCalendar.getDayOfWeekIndex() == 6) 0 else NotRetardedCalendar.getDayOfWeekIndex()

            // add the current and next week
            addWeek(mensaMenu.currentWeek, dayCurrent).join()
            addWeek(mensaMenu.nextWeek, 0).join()

            // show a info if there are no more menus
            if (binding.linLayoutMensa.childCount == 0) {
                val txtViewInfo = TextViewInfo(context!!).set {
                    txt = resources.getString(R.string.no_more_meals)
                }
                withContext(Dispatchers.Main) { binding.linLayoutMensa.addView(txtViewInfo) }
            }
        }
    }

    /**
     * add all menus from dayStart to Friday for a given week
     * @param menusWeek menu of type MensaWeek you want to add
     * @param dayStart the first day of the week to add
     */
    private fun addWeek(menusWeek: MensaWeek, dayStart: Int) = GlobalScope.launch(Dispatchers.Default) {

        withContext(Dispatchers.Main) {
            // only add the days dayStart to Fri since the mensa is closed on Sat/Sun
            for (dayIndex in dayStart..4) {
                var helpMeal = MealLinearLayout(context)
                val dayCardView = DayCardView(context!!)

                if(menusWeek.days[dayIndex].meals.isNotEmpty())
                    dayCardView.setDayHeading(menusWeek.days[dayIndex].meals[0].day)

                for (meal in menusWeek.days[dayIndex].meals) {
                    val mealLayout = MealLinearLayout(context)
                    mealLayout.setMeal(meal)

                    if(meal.heading != "Buffet" || Preferences.showBuffet) {
                        dayCardView.getLinLayoutDay().addView(mealLayout)
                        helpMeal = mealLayout
                    }
                }

                helpMeal.disableDivider()

                if(dayCardView.getLinLayoutDay().childCount > 2)
                    binding.linLayoutMensa.addView(dayCardView)
            }
        }

    }

    /**
     * initialize the actions
     */
    private fun initActions() {
        // set the refresh listener
        binding.refreshLayoutMensa.setOnRefreshListener {
            updateMensaScreen()
        }
    }

    /**
     * refresh the mensa cache and update the mensa screen
     */
    private fun updateMensaScreen() = GlobalScope.launch(Dispatchers.Default) {
        CacheController.updateMensaMenu(context!!).join() // blocking since we want the new data

        withContext(Dispatchers.Main) {
            // remove all menus from the layout
            binding.linLayoutMensa.removeAllViews()

            // add the refreshed menus
            val dayCurrent = if (NotRetardedCalendar.getDayOfWeekIndex() == 6) 0 else NotRetardedCalendar.getDayOfWeekIndex()

            // add the current and next week
            addWeek(mensaMenu.currentWeek, dayCurrent).join()
            addWeek(mensaMenu.nextWeek, 0).join()

            binding.refreshLayoutMensa.isRefreshing = false

            // show a info if there are no more menus
            if (binding.linLayoutMensa.childCount == 0) {
                val txtViewInfo = TextViewInfo(context!!).set {
                    txt = resources.getString(R.string.no_more_meals)
                }
                binding.linLayoutMensa.addView(txtViewInfo)
            }
        }
    }

}
