package app.furmeet.events.system.schedule.adapters

import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.database.DataSetObserver
import android.text.InputType
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager.LayoutParams
import android.widget.EditText
import android.widget.ListAdapter
import android.widget.TextView
import android.widget.TimePicker
import app.furmeet.events.system.helper.*
import app.furmeet.events.system.schedule.abstractDataTypes.GregorianCalendarRange
import app.furmeet.events.system.schedule.abstractDataTypes.convention.Event
import app.furmeet.events.system.schedule.abstractDataTypes.managed.Actions
import app.furmeet.events.system.schedule.abstractDataTypes.managed.AttendeeConFavorite
import app.furmeet.events.system.schedule.managers.ScheduleManagerGetter
import app.furmeet.events.bff.R
//import kotlinx.android.synthetic.main.oldpart_schedule_eventlistitem.view.*
import java.util.*
import kotlin.math.roundToInt


class HourlyPlannedEventDialogListAdapter(
        private val activity: Activity,
        private val container: AlertDialog,
        private val dayPart: GregorianCalendarRange
) : ListAdapter {
    private val scheduleManager = ScheduleManagerGetter.get()
    private val favoritableEventsInTimeInterval =
            scheduleManager.convention.events.filter {
                it.timeRange in dayPart
            }.filterNot {
                it in scheduleManager.attendeeFavorites
            }.filterNot {
                it.hiddenFromTimeTable
            }
    private val emptyLanguageStrings = mapOf(
            Language.PT to "",
            Language.EN to "",
            Language.ES to ""
    )
    private val emptyEvent = Event(
            "",
            "",
            listOf(),
            emptyLanguageStrings,
            emptyLanguageStrings,
            emptyLanguageStrings,
            dayPart,
            listOf(),
            listOf(),
            listOf(),
            getRuntimeLanguage(),
            false,
            null
    )
    private val availableEvents = listOf(
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply { kind = Actions.Intention.SLEEP },
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply { kind = Actions.Intention.EAT },
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply { kind = Actions.Intention.SHOWER },
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply { kind = Actions.Intention.NOTHING },
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply { kind = Actions.Intention.ARRIVE },
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply { kind = Actions.Intention.DEPARTURE },
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply {
                kind = Actions.Intention.ROOMPARTY
                name = R.string.schedule_roomparty.getString()
            },
            AttendeeConFavorite(scheduleManager.convention, emptyEvent).apply {
                kind = Actions.Intention.CUSTOM
                name = R.string.schedule_custom.getString()
            }
    )

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val event = getItem(position)
        val view = convertView
                ?: parent.context.layoutInflater.inflate(R.layout.oldpart_schedule_eventlistitem)
        view.setOnClickListener {
            when (event.kind) {
                Actions.Intention.ROOMPARTY -> {
                    event.name = ""
                    val roomPartyRange = GregorianCalendarRange(dayPart.start.timeInMillis, dayPart.start.timeInMillis)
                    val timePickerStart = TimePicker(parent.context)
                    val dialogWhenStart = AlertDialog.Builder(container.context).create()
                    timePickerStart.setIs24HourView(true)
                    timePickerStart.compatHour = dayPart.start.get(GregorianCalendar.HOUR_OF_DAY)
                    timePickerStart.compatMinute = dayPart.start.get(GregorianCalendar.MINUTE)
                    dialogWhenStart.setView(timePickerStart)
                    dialogWhenStart.setTitle(R.string.schedule_roomparty_starttime_question.getString())
                    dialogWhenStart.setButton(AlertDialog.BUTTON_NEUTRAL, R.string.dialog_cancel.getString()) { _: DialogInterface, _: Int ->
                        dialogWhenStart.dismiss()
                    }
                    dialogWhenStart.setButton(AlertDialog.BUTTON_POSITIVE, R.string.dialog_confirm.getString()) { _: DialogInterface, _: Int ->
                        roomPartyRange.start.set(
                                GregorianCalendar.HOUR_OF_DAY,
                                timePickerStart.compatHour
                        )
                        roomPartyRange.start.set(
                                GregorianCalendar.MINUTE,
                                timePickerStart.compatMinute
                        )
                        val dialogWhen = AlertDialog.Builder(container.context).create()
                        val timePicker = TimePicker(parent.context)
                        timePicker.setIs24HourView(true)
                        timePicker.compatHour = dayPart.finish.get(GregorianCalendar.HOUR_OF_DAY)
                        timePicker.compatMinute = dayPart.finish.get(GregorianCalendar.MINUTE)
                        dialogWhen.setView(timePicker)
                        dialogWhen.setTitle(R.string.schedule_roomparty_endtime_question.getString())
                        dialogWhen.setButton(AlertDialog.BUTTON_NEUTRAL, R.string.dialog_cancel.getString()) { _: DialogInterface, _: Int ->
                            dialogWhen.dismiss()
                        }
                        dialogWhen.setButton(AlertDialog.BUTTON_POSITIVE, R.string.dialog_confirm.getString()) { _: DialogInterface, _: Int ->
                            roomPartyRange.finish.set(
                                    GregorianCalendar.HOUR_OF_DAY,
                                    timePicker.compatHour
                            )
                            roomPartyRange.finish.set(
                                    GregorianCalendar.MINUTE,
                                    timePicker.compatMinute
                            )
                            if (roomPartyRange.finish <= roomPartyRange.start)
                                roomPartyRange.finish.timeInMillis += 1000L * 24 * 3600
                            event.timeRange = roomPartyRange
                            val textBoxWhere = EditText(parent.context)
                            textBoxWhere.inputType = InputType.TYPE_CLASS_TEXT
                            textBoxWhere.text.insert(0, R.string.schedule_roomparty_where.getString())
                            val dialogWhere = AlertDialog.Builder(container.context).create()
                            dialogWhere.setTitle(R.string.schedule_roomparty_where_question)
                            dialogWhere.setView(textBoxWhere, 4.asDpToPx.roundToInt(), 0, 4.asDpToPx.roundToInt(), 0)
                            dialogWhere.setButton(AlertDialog.BUTTON_NEUTRAL, R.string.dialog_cancel.getString()) { _: DialogInterface, _: Int ->
                                dialogWhere.dismiss()
                            }
                            dialogWhere.setOnShowListener {
                                textBoxWhere.showSoftInputOnFocus = true
                                textBoxWhere.requestFocus()
                                val idx = textBoxWhere.text.toString().indexOf("1234")
                                textBoxWhere.setSelection(idx, idx + 4)
                            }
                            dialogWhere.setButton(AlertDialog.BUTTON_POSITIVE, R.string.dialog_confirm.getString()) { _: DialogInterface, _: Int ->
                                val text = textBoxWhere.text.toString().trim()
                                if (text.isNotEmpty()) {
                                    dialogWhere.dismiss()
                                    event.roomName = text
                                    val textBoxName = EditText(parent.context)
                                    textBoxName.inputType = InputType.TYPE_CLASS_TEXT
                                    textBoxName.text.insert(0, R.string.schedule_roomparty_name.getString())
                                    val dialogName = AlertDialog.Builder(container.context).create()
                                    dialogName.setTitle(R.string.schedule_roomparty_name_question.getString())
                                    dialogName.setView(textBoxName, 4.asDpToPx.roundToInt(), 0, 4.asDpToPx.roundToInt(), 0)
                                    dialogName.setButton(AlertDialog.BUTTON_NEUTRAL, R.string.dialog_cancel.getString()) { _: DialogInterface, _: Int ->
                                        dialogName.dismiss()
                                    }
                                    dialogName.setOnShowListener {
                                        textBoxName.showSoftInputOnFocus = true
                                        textBoxName.requestFocus()
                                        val idx = textBoxName.text.toString().indexOf("Xyz")
                                        textBoxName.setSelection(idx, idx + 3)
                                    }
                                    dialogName.setButton(AlertDialog.BUTTON_POSITIVE, R.string.dialog_confirm.getString()) { _: DialogInterface, _: Int ->
                                        val name = textBoxName.text.toString().trim()
                                        if (text.isNotEmpty()) {
                                            dialogName.dismiss()
                                            event.name = name
                                            scheduleManager.attendeeFavorites.add(event)
                                            activity.begForNotificationPermission()
                                        }
                                    }
                                    dialogName.window!!.setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE)
                                    dialogName.show()
                                }
                            }
                            dialogWhere.window!!.setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE)
                            dialogWhere.show()
                        }
                        dialogWhen.show()
                        container.dismiss()
                    }
                    dialogWhenStart.show()
                    container.dismiss()
                }
                Actions.Intention.CUSTOM -> {
                    container.dismiss()
                    val start = dayPart.start.timeInMillis.formatAsHoursAndMinutes()
                    val finish = dayPart.finish.timeInMillis.formatAsHoursAndMinutes()
                    event.name = ""
                    val textBox = EditText(parent.context)
                    textBox.inputType = InputType.TYPE_CLASS_TEXT
                    val dialog = AlertDialog.Builder(container.context).create()
                    dialog.setTitle(R.string.schedule_add_what.getString().format(start, finish))
                    dialog.setView(textBox, 4.asDpToPx.roundToInt(), 0, 4.asDpToPx.roundToInt(), 0)
                    dialog.setButton(AlertDialog.BUTTON_NEUTRAL, R.string.dialog_cancel.getString()) { _: DialogInterface, _: Int ->
                        dialog.dismiss()
                    }
                    dialog.setButton(AlertDialog.BUTTON_POSITIVE, R.string.dialog_confirm.getString()) { _: DialogInterface, _: Int ->
                        val text = textBox.text.toString().trim()
                        if (text.isNotEmpty()) {
                            dialog.dismiss()
                            event.name = text
                            scheduleManager.attendeeFavorites.add(event)
                            activity.begForNotificationPermission()
                        }
                    }
                    dialog.setOnShowListener {
                        textBox.showSoftInputOnFocus = true
                        textBox.requestFocus()
                    }
                    dialog.window!!.setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE)
                    dialog.show()
                }
                else -> {
                    scheduleManager.attendeeFavorites.add(event)
                    activity.begForNotificationPermission()
                    container.dismiss()
                }
            }
        }
        view.findViewById<TextView>(R.id.text_planned_event).text = event.getString()
        view.findViewById<TextView>(R.id.text_planned_event_room).text = event.getSecondaryEditString()
        return view
    }

    override fun getItem(position: Int): AttendeeConFavorite = availableEvents[position]
    override fun getCount(): Int = availableEvents.size
    override fun getItemId(position: Int): Long = getItem(position).hashCode().toLong()
    override fun getItemViewType(position: Int): Int = 0
    override fun getViewTypeCount(): Int = 1
    override fun isEmpty(): Boolean = false
    override fun isEnabled(position: Int): Boolean = true
    override fun hasStableIds(): Boolean = true
    override fun areAllItemsEnabled(): Boolean = true
    override fun registerDataSetObserver(observer: DataSetObserver?) {}
    override fun unregisterDataSetObserver(observer: DataSetObserver?) {}
}
