package org.libre.agosto.p2play

import android.os.AsyncTask
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.android.material.tabs.TabLayoutMediator
import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.libre.agosto.p2play.ajax.Accounts
import org.libre.agosto.p2play.databinding.ActivityAccountBinding
import org.libre.agosto.p2play.databinding.ActivityMainBinding
import org.libre.agosto.p2play.fragmentAdapters.AccountAdapter
import org.libre.agosto.p2play.models.AccountModel

class AccountActivity : AppCompatActivity() {
    private lateinit var binding: ActivityAccountBinding
    private val client = Accounts()
    private lateinit var accountId: String
    private lateinit var adapter: AccountAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAccountBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)

        accountId = this.intent.extras?.getString("accountId")!!

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        binding.toolbar.setNavigationOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        adapter = AccountAdapter(supportFragmentManager, lifecycle)
        binding.viewpager.adapter = adapter

        adapter.accountId = accountId

        TabLayoutMediator(binding.tabs, binding.viewpager, false, false) { tab, position ->
            tab.text = adapter.get(position)
        }.attach()
    }

    override fun onResume() {
        super.onResume()
        getChannelInfo()
    }

    private fun getChannelInfo() {
        CoroutineScope(Dispatchers.IO).launch {
            val account = client.get(accountId)

            withContext(Dispatchers.Main) {
                binding.collapsingToolbar.title = account.displayName
                adapter.account = account
                if (account.avatars.size > 0) {
                    Picasso.get().load("https://${ManagerSingleton.url}${account.avatars.last().path}").into(binding.profileImage)
                }
            }
        }
    }
}