package com.sambath.kunkhmer.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.remote.EventInfo
import com.squareup.picasso.Picasso
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone

class EventAdapter(var cardList: MutableList<EventInfo>) : RecyclerView.Adapter<EventAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventAdapter.ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.layout_event_item_card, parent, false)
        return EventAdapter.ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: EventAdapter.ViewHolder, position: Int) {
        val currentItem = cardList[position]

        Picasso.get().load(R.drawable.default_background).into(holder.imageView)
        holder.subTitleTextView.text = currentItem.eventInfoId.desc
        holder.titleTextView.text = currentItem.eventInfoId.title
        holder.dateTitleTextView.text = parseAndFormatDate(currentItem.eventInfoId.createdAt)
    }

    override fun getItemCount() = cardList.size

    class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        val imageView: ImageView = itemView.findViewById(R.id.imageView)
        val subTitleTextView: TextView = itemView.findViewById(R.id.subTitleTextView)
        val titleTextView: TextView = itemView.findViewById(R.id.titleTextView)
        val dateTitleTextView: TextView = itemView.findViewById(R.id.dateTitleTextView)
    }

    private fun parseAndFormatDate(dateString: String): String {
        // Create a SimpleDateFormat for parsing the date string
        val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
        parser.timeZone = TimeZone.getTimeZone("UTC")

        // Parse the date
        val date = parser.parse(dateString)

        // Create a SimpleDateFormat for formatting the date
        val formatter = SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault())
        formatter.timeZone = TimeZone.getDefault() // Use local timezone

        // Format the date
        return formatter.format(date)
    }
}