package bou.amine.apps.readerforselfossv2.android

import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import bou.amine.apps.readerforselfossv2.android.databinding.ActivityReaderBinding
import bou.amine.apps.readerforselfossv2.android.fragments.ArticleFragment
import bou.amine.apps.readerforselfossv2.model.SelfossModel
import bou.amine.apps.readerforselfossv2.repository.Repository
import bou.amine.apps.readerforselfossv2.service.AppSettingsService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kodein.di.DIAware
import org.kodein.di.android.closestDI
import org.kodein.di.instance

class ReaderActivity : AppCompatActivity(), DIAware {

    private var currentItem: Int = 0

    private lateinit var toolbarMenu: Menu

    private lateinit var binding: ActivityReaderBinding

    override val di by closestDI()
    private val repository: Repository by instance()
    private val appSettingsService: AppSettingsService by instance()

    private fun showMenuItem(willAddToFavorite: Boolean) {
        if (willAddToFavorite) {
            toolbarMenu.findItem(R.id.star).icon?.setTint(Color.WHITE)
        } else {
            toolbarMenu.findItem(R.id.star).icon?.setTint(Color.RED)
        }
    }

    private fun canFavorite() {
        showMenuItem(true)
    }

    private fun canRemoveFromFavorite() {
        showMenuItem(false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityReaderBinding.inflate(layoutInflater)
        val view = binding.root

        setContentView(view)

        setSupportActionBar(binding.toolBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)

        if (allItems.isEmpty()) {
            finish()
        }

        currentItem = intent.getIntExtra("currentItem", 0)

        readItem(allItems[currentItem])

        binding.pager.adapter = ScreenSlidePagerAdapter(this)
        binding.pager.setCurrentItem(currentItem, false)
    }

    override fun onResume() {
        super.onResume()

        binding.indicator.setViewPager(binding.pager)
    }

    private fun readItem(item: SelfossModel.Item) {
        if (appSettingsService.isMarkOnScrollEnabled()) {
            CoroutineScope(Dispatchers.IO).launch {
                repository.markAsRead(item)
            }
        }
    }

    override fun onSaveInstanceState(oldInstanceState: Bundle) {
        super.onSaveInstanceState(oldInstanceState)
        oldInstanceState.clear()
    }

    private inner class ScreenSlidePagerAdapter(fa: FragmentActivity) :
        FragmentStateAdapter(fa) {

        override fun getItemCount(): Int = allItems.size

        override fun createFragment(position: Int): Fragment =
            ArticleFragment.newInstance(allItems[position])

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_DOWN -> {
                val currentFragment =
                    supportFragmentManager.findFragmentByTag("f" + binding.pager.currentItem) as ArticleFragment
                currentFragment.scrollDown()
                true
            }
            KeyEvent.KEYCODE_VOLUME_UP -> {
                val currentFragment =
                    supportFragmentManager.findFragmentByTag("f" + binding.pager.currentItem) as ArticleFragment
                currentFragment.scrollUp()
                true
            }
            else -> {
                super.onKeyDown(keyCode, event)
            }
        }
    }

    private fun alignmentMenu() {
        val showJustify = appSettingsService.getActiveAllignment() == AppSettingsService.ALIGN_LEFT
        toolbarMenu.findItem(R.id.align_left).isVisible = !showJustify
        toolbarMenu.findItem(R.id.align_justify).isVisible = showJustify
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.reader_menu, menu)
        toolbarMenu = menu

        if (allItems.isNotEmpty() && allItems[currentItem].starred) {
            canRemoveFromFavorite()
        } else {
            canFavorite()
        }
        alignmentMenu()

        binding.pager.registerOnPageChangeCallback(
            object : ViewPager2.OnPageChangeCallback() {

                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)

                    if (allItems[position].starred) {
                        canRemoveFromFavorite()
                    } else {
                        canFavorite()
                    }
                    readItem(allItems[position])
                }
            }
        )

        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        fun afterSave() {
            allItems[binding.pager.currentItem] =
                allItems[binding.pager.currentItem].toggleStar()
            canRemoveFromFavorite()
        }

        fun afterUnsave() {
            allItems[binding.pager.currentItem] = allItems[binding.pager.currentItem].toggleStar()
            canFavorite()
        }

        when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                return true
            }
            R.id.star -> {
                if (allItems[binding.pager.currentItem].starred) {
                    CoroutineScope(Dispatchers.IO).launch {
                        repository.unstarr(allItems[binding.pager.currentItem])
                        // TODO: Handle failure
                    }
                    afterUnsave()
                } else {
                    CoroutineScope(Dispatchers.IO).launch {
                        repository.starr(allItems[binding.pager.currentItem])
                        // TODO: Handle failure
                    }
                    afterSave()
                }
            }
            R.id.align_left -> {
                switchAlignmentSetting(AppSettingsService.ALIGN_LEFT)
                refreshFragment()
            }
            R.id.align_justify -> {
                switchAlignmentSetting(AppSettingsService.JUSTIFY)
                refreshFragment()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun switchAlignmentSetting(allignment: Int) {
        appSettingsService.changeAllignment(allignment)
        alignmentMenu()
    }

    private fun refreshFragment() {
        finish()
        overridePendingTransition(0, 0)
        startActivity(intent)
        overridePendingTransition(0, 0)
    }

    companion object {
        var allItems: ArrayList<SelfossModel.Item> = ArrayList()
    }
}
