package net.pokeranalytics.android.ui.fragment.components

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.DialogInterface
import android.text.format.DateFormat
import android.widget.DatePicker
import android.widget.TimePicker
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.fragment.components.bottomsheet.BottomSheetDelegate
import net.pokeranalytics.android.ui.view.RowRepresentable
import java.util.*

class DateTimePickerManager : DatePickerDialog.OnDateSetListener,
	TimePickerDialog.OnTimeSetListener {

	private var context: Context? = null

	lateinit var row: RowRepresentable
	lateinit var bottomSheetDelegate: BottomSheetDelegate
	lateinit var calendar: Calendar

	companion object {
		fun create(
            context: Context,
            row: RowRepresentable,
            bottomSheetDelegate: BottomSheetDelegate,
            date: Date?
		) : DateTimePickerManager {

			val calendar = Calendar.getInstance()
			calendar.time = date ?: Date()

			val dateTimePickerManager = DateTimePickerManager()
			dateTimePickerManager.context = context
			dateTimePickerManager.row = row
			dateTimePickerManager.bottomSheetDelegate = bottomSheetDelegate
			dateTimePickerManager.calendar = calendar

			dateTimePickerManager.showDatePicker()

			return dateTimePickerManager
		}
	}

	override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
		calendar.set(Calendar.YEAR, year)
		calendar.set(Calendar.MONTH, month)
		calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
		showTimePicker()
	}

	override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
		calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
		calendar.set(Calendar.MINUTE, minute)
		bottomSheetDelegate.setValue(calendar.time, row)
	}

	/**
	 * Show the date picker
	 */
	private fun showDatePicker() {
		val year = calendar.get(Calendar.YEAR)
		val month = calendar.get(Calendar.MONTH)
		val day = calendar.get(Calendar.DAY_OF_MONTH)
		context?.let {
			val datePickerDialog = DatePickerDialog(it, this, year, month, day)
			datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, it.getString(R.string.clear)) { dialog, _ ->
				bottomSheetDelegate.clickOnClear(row)
				dialog.dismiss()
			}
			datePickerDialog.show()
		}
	}

	/**
	 * Show the time picker
	 */
	private fun showTimePicker() {
		val hour = calendar.get(Calendar.HOUR_OF_DAY)
		val minute = calendar.get(Calendar.MINUTE)
		context?.let {
			val timePickerDialog = TimePickerDialog(context, this, hour, minute, DateFormat.is24HourFormat(context))
			timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, it.getString(R.string.clear)) { dialog, _ ->
				bottomSheetDelegate.clickOnClear(row)
				dialog.dismiss()
			}
			timePickerDialog.show()
		}
	}

}