package com.didvan.didvanapp

import android.annotation.SuppressLint
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.SharedPreferences
import android.net.Uri
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.RemoteViews
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.NetworkPolicy
import com.squareup.picasso.Picasso
import com.squareup.picasso.Transformation
import es.antonborri.home_widget.HomeWidgetLaunchIntent
import es.antonborri.home_widget.HomeWidgetProvider
import es.antonborri.home_widget.HomeWidgetBackgroundIntent
import java.lang.Exception


/**
 * Implementation of App Widget functionality.
 */
class FavWidget : HomeWidgetProvider() {

    @SuppressLint("RemoteViewLayout")
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray,
        widgetData: SharedPreferences
    ) {
        appWidgetIds.forEach { widgetId ->
            val views = RemoteViews(context.packageName, R.layout.favourite_widget).apply {

                // Open App on Widget Click
                val pendingIntent = HomeWidgetLaunchIntent.getActivity(
                    context,
                    MainActivity::class.java
                )
                setOnClickPendingIntent(R.id.logo_btn, pendingIntent)

                val responses: ArrayList<WidgetResponse> = ArrayList();
                val token = widgetData.getString("token", "").toString()

                if (token.isEmpty()) {
                    setViewVisibility(R.id.list_lay, INVISIBLE)
                    setViewVisibility(R.id.setting_btn, INVISIBLE)
                    setViewVisibility(R.id.empty_lay, VISIBLE)
                    setOnClickPendingIntent(R.id.empty_lay, pendingIntent)


                } else {
                    setViewVisibility(R.id.list_lay, VISIBLE)
                    setViewVisibility(R.id.setting_btn, VISIBLE)
                    setViewVisibility(R.id.empty_lay, GONE)

                    for (i in 0..2) {
                        responses.add(
                            WidgetResponse(
                                id = widgetData.getString("id${i + 1}", "")?.toInt() ?: 0,
                                title = widgetData.getString("title${i + 1}", "").toString(),
                                createdAt = widgetData.getString("createdAt${i + 1}", "")
                                    .toString(),
                                type = widgetData.getString("type${i + 1}", "").toString(),
                                link = widgetData.getString("link${i + 1}", "").toString(),
                                category = widgetData.getString("category${i + 1}", "").toString(),
                                image = widgetData.getString("image${i + 1}", "").toString(),
                            )
                        )
                    }

                    setTextViewText(R.id.first_title, responses[0].title.toString())
                    setTextViewText(R.id.middle_title, responses[1].title.toString())
                    setTextViewText(R.id.last_title, responses[2].title.toString())
//
                    setTextViewText(R.id.first_tag, responses[0].category)
                    setTextViewText(R.id.middle_tag, responses[1].category)
                    setTextViewText(R.id.last_tag, responses[2].category)

                    setTextViewText(R.id.first_duration, responses[0].createdAt)
                    setTextViewText(R.id.middle_duration, responses[1].createdAt)
                    setTextViewText(R.id.last_duration, responses[2].createdAt)

                    try {
                        Picasso.get()
                            .load("https://api.didvan.app${responses[0].image}?accessToken=${token}")
                            .transform(RoundedTransformation(10, 0))
                            .networkPolicy(NetworkPolicy.NO_STORE)
                            .memoryPolicy(MemoryPolicy.NO_STORE)
                            .error(R.drawable.test)
                            .resize(100, 100)
                            .into(this, R.id.first_image, appWidgetIds);
                    } catch (e: Exception) {

                    }

                    try {
                        Picasso.get()
                            .load("https://api.didvan.app${responses[1].image}?accessToken=${token}")
                            .transform(RoundedTransformation(10, 0))
                            .networkPolicy(NetworkPolicy.NO_STORE)
                            .memoryPolicy(MemoryPolicy.NO_STORE)
                            .error(R.drawable.test)
                            .resize(100, 100)
                            .into(this, R.id.middle_image, appWidgetIds);
                    } catch (e: Exception) {

                    }

                    try {
                        Picasso.get()
                            .load("https://api.didvan.app${responses[2].image}?accessToken=${token}")
                            .transform(RoundedTransformation(10, 0))
                            .networkPolicy(NetworkPolicy.NO_STORE)
                            .memoryPolicy(MemoryPolicy.NO_STORE)
                            .error(R.drawable.test)
                            .resize(100, 100)
                            .into(this, R.id.last_image, appWidgetIds);
                    } catch (e: Exception) {

                    }


                    // Pending intent to update counter on button click
                    val settingIntent = HomeWidgetBackgroundIntent.getBroadcast(
                        context, Uri.parse("myAppWidget://setting")

                    )
                    setOnClickPendingIntent(R.id.setting_btn, settingIntent)

                    val rowFirst = HomeWidgetBackgroundIntent.getBroadcast(
                        context,
                        Uri.parse("myAppWidget://rowFirst")

                    )
                    setOnClickPendingIntent(R.id.first_row, rowFirst)

                    val rowMiddle = HomeWidgetBackgroundIntent.getBroadcast(
                        context,
                        Uri.parse("myAppWidget://rowMiddle")

                    )
                    setOnClickPendingIntent(R.id.middle_row, rowMiddle)

                    val rowLast = HomeWidgetBackgroundIntent.getBroadcast(
                        context,
                        Uri.parse("myAppWidget://rowLast")

                    )
                    setOnClickPendingIntent(R.id.last_row, rowLast)
                }


            }
            appWidgetManager.updateAppWidget(widgetId, views)
        }
    }

}