package cz.jacktech.gugorganizer.ui.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView

import org.joda.time.DateTime
import org.joda.time.Period
import org.joda.time.PeriodType
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import org.joda.time.format.PeriodFormatter
import org.joda.time.format.PeriodFormatterBuilder
import org.w3c.dom.Text

import java.util.ArrayList

import cz.jacktech.gugorganizer.R
import cz.jacktech.gugorganizer.network.api_objects.GugEventOccurrence

import kotlinx.android.synthetic.event_list_item.view.*
import org.jetbrains.anko.text

/**
 * Created by toor on 13.8.15.
 */
public class EventsAdapter(private val mContext: Context) : RecyclerView.Adapter<EventsAdapter.ViewHolder>() {

    private var mEvents = ArrayList<GugEventOccurrence>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.event_list_item, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val event = mEvents.get(position)
        holder.bindEvent(event)
    }

    override fun getItemCount(): Int {
        return mEvents.size()
    }

    public fun setEvents(events: ArrayList<GugEventOccurrence>) {
        mEvents.clear()
        mEvents.addAll(events)
        notifyDataSetChanged()
    }

    public fun loadEvents(events: ArrayList<GugEventOccurrence>) {
        mEvents = events
        notifyDataSetChanged()
    }

    public fun clear() {
        val count = mEvents.size()
        mEvents.clear()
        notifyItemRangeRemoved(0, count - 1)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindEvent(event: GugEventOccurrence) {
            itemView.event_name.text = event.name!!
            val eventDate = DateTime(event.dateFrom)
            val now = DateTime()
            if (eventDate.isBefore(now)) {
                val fmt = DateTimeFormat.forPattern("dd.MM.yyyy, HH:mm")
                itemView.event_info.setText(fmt.print(eventDate))
            } else {
                val toEventBeginning = Period(now, eventDate, PeriodType.dayTime())
                val fmt = PeriodFormatterBuilder().appendDays().appendSuffix("d ").appendHours().appendSuffix("h ").appendMinutes().appendSuffix("m ").toFormatter()
                itemView.event_info.setText(itemView.getContext().getString(R.string.event_in) + fmt.print(toEventBeginning))
                //todo: implement automatic refreshing
            }
        }

    }

}
