/**
 * 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.uicomponents

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.cardview.widget.CardView
import org.mosad.seil0.projectlaogai.databinding.CardviewDayBinding
import org.mosad.seil0.projectlaogai.util.DataTypes
import org.mosad.seil0.projectlaogai.util.TimetableDay
import java.text.SimpleDateFormat
import java.util.*

class DayCardView(context: Context) : CardView(context) {

    private var binding = CardviewDayBinding.inflate(LayoutInflater.from(context), this, true)
    private val formatter = SimpleDateFormat("E dd.MM", Locale.getDefault())

    init {
        this.setBackgroundColor(Color.TRANSPARENT) // workaround to prevent a white border
    }

    fun getLinLayoutDay() : LinearLayout {
        return binding.linearDay
    }

    fun setDayHeading(heading: String) {
        binding.textDayHeading.text = heading
    }

    /**
     * add the lessons of one day to the dayCardView
     * @param timetable a timetable containing the day (and it's lessons) to be added
     */
    fun addTimetableDay(timetable: TimetableDay, daysToAdd: Int) {
        var lastLesson = LessonLinearLayout(context)

        // set the heading
        val cal = Calendar.getInstance()
        cal.add(Calendar.DATE, daysToAdd)
        binding.textDayHeading.text = formatter.format(cal.time)

        // for every timeslot of that timetable
        timetable.timeslots.forEachIndexed { tsIndex, timeslot ->
            timeslot.forEach { lesson ->
                if (lesson.lessonSubject.isNotEmpty()) {

                    val lessonLayout = LessonLinearLayout(context)
                    lessonLayout.setLesson(lesson, DataTypes().times[tsIndex])
                    binding.linearDay.addView(lessonLayout)

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

                    lastLesson = lessonLayout
                }
            }

        }

        lastLesson.disableDivider() // disable the divider for the last lesson of the day
    }

}