package app.furmeet.events.system.schedule

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.res.ColorStateList
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.fragment.app.FragmentPagerAdapter
import app.furmeet.events.bff.R
import app.furmeet.events.bff.databinding.ActivityScheduleBinding
import app.furmeet.events.system.AssetImageViewerActivity
import app.furmeet.events.system.SplashActivity
import app.furmeet.events.system.TranslatableAppCompatActivityWithScheduleServiceWrapped
import app.furmeet.events.system.developer.DeveloperActivity
import app.furmeet.events.system.helper.*
import app.furmeet.events.system.schedule.abstractDataTypes.managed.AttendeeConFavorite
import app.furmeet.events.system.schedule.adapters.DaysPagerAdapter
import app.furmeet.events.system.schedule.adapters.LanguageSelectorListAdapter
import com.google.gson.GsonBuilder
import com.google.zxing.integration.android.IntentIntegrator


class ScheduleActivity : TranslatableAppCompatActivityWithScheduleServiceWrapped() {
    lateinit var binding: ActivityScheduleBinding
    private lateinit var pagerAdapter: FragmentPagerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        ActivitiesForFragments[this.javaClass.simpleName] = this
        super.onCreate(savedInstanceState)
        binding = ActivityScheduleBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        setSupportActionBar(binding.toolbar)
        resourcesAliased = this.resources

        scheduleManager.convention.colorScheme?.primaryRegular?.let {
            window!!.statusBarColor = it
            binding.appBarLayout.setBackgroundColor(it)
            binding.toolbar.backgroundTintList = ColorStateList.valueOf(it)
            binding.tabs.setBackgroundColor(it)
        }
        scheduleManager.convention.colorScheme?.accentColor?.let {
            binding.fab.backgroundTintList = ColorStateList.valueOf(it)
            binding.tabs.setSelectedTabIndicatorColor(it)
        }

        scheduleManager.onAttendeeIntentionsChanged()
        binding.toolbar.title = scheduleManager.convention.name
        binding.toolbar.subtitle = scheduleManager.convention.theme.solved
        pagerAdapter = DaysPagerAdapter(supportFragmentManager, scheduleManager)
        binding.container.adapter = pagerAdapter
        binding.tabs.fullSetup(binding.container)

        binding.toolbar.setOnLongClickListener { clickView ->
            Intent(clickView.context, AssetImageViewerActivity::class.java).apply {
                putExtra("asset", scheduleManager.currentSplashAsset)
                startActivity(this)
            }
            true
        }

        binding.container.offscreenPageLimit = pagerAdapter.count

        binding.fab.setOnClickListener {
            Intent(this, FavoritesActivity::class.java).apply {
                startActivity(this)
            }
        }
        binding.fab.isLongClickable = true
        binding.fab.setOnLongClickListener {
            longToast(R.string.schedule_events_favorites.getString())
            true
        }
        val uri = intent.getStringExtra("uri")
        if(!uri.isNullOrBlank()) {
            unrecognizedQrScan(uri)
        }
        onBackPressDispatcherAddCallbackCompat { handleBackPressed() }
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_schedule, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_clear_planning -> {
                val dialog = AlertDialog.Builder(this).create()
                dialog.setTitle(R.string.schedule_clear_planning_question.getString())
                dialog.setMessage(R.string.this_cannot_be_undone.getString())
                dialog.setButton(AlertDialog.BUTTON_NEUTRAL, R.string.dialog_cancel.getString()) { _: DialogInterface, _: Int ->
                    dialog.dismiss()
                }
                dialog.setButton(AlertDialog.BUTTON_NEGATIVE, R.string.dialog_confirm.getString()) { _: DialogInterface, _: Int ->
                    dialog.dismiss()
                    scheduleManager.clearIntentions()
                    scheduleManager.onAttendeeIntentionsChanged()
                }
                dialog.show()
                true
            }
            R.id.action_about -> {
                Intent(this, DeveloperActivity::class.java).apply {
                    startActivity(this)
                }
                true
            }
            R.id.action_search_filter -> {
                Intent(this, SearchFilterActivity::class.java).apply {
                    startActivity(this)
                }
                true
            }
            R.id.action_scan_qr_code -> {
                IntentIntegrator(this).apply {
                    setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES)
                    setOrientationLocked(true)
                    setBarcodeImageEnabled(false)
                    setBeepEnabled(false)
                    initiateScan()
                }
                true
            }
            R.id.action_change_language -> {
                val languages = Language.values().toList()
                val dialog = AlertDialog.Builder(this).setAdapter(
                        LanguageSelectorListAdapter(languages)
                ) { dialogInterface: DialogInterface, which: Int ->
                    val newLang = languages[which]
                    dialogInterface.dismiss()
                    val lm = LocaleManager(this.baseContext)
                    lm.language = newLang
                    restartWholeApplication()
                }.create()
                dialog.setTitle(R.string.change_language.getString())
                dialog.setButton(AlertDialog.BUTTON_NEUTRAL, R.string.dialog_cancel.getString()) { _: DialogInterface, _: Int ->
                    dialog.dismiss()
                }
                dialog.show()
                true
            }
            R.id.action_app_privacy_policy -> {
                AlertDialog.Builder(this)
                    .setTitle(R.string.app_privacy_policy)
                    .setMessage(R.string.app_privacy_policy_content)
                    .setNegativeButton(R.string.dialog_close) { dialog, _ -> dialog.dismiss() }
                    .create()
                    .show()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun restartWholeApplication() {
        this.finish()
        val intent = Intent(this, SplashActivity::class.java)
        intent.flags =
                Intent.FLAG_ACTIVITY_NEW_TASK or
                        Intent.FLAG_ACTIVITY_TASK_ON_HOME
        intent.putExtra("fastStart", true)
        this.startActivity(intent)
    }

    override fun finish() {
        scheduleManager.finish()
        super.finish()
    }

    private fun handleBackPressed() {
        if (binding.tabs.selectedTabPosition == 0)
            finish()
        else
            binding.container.setCurrentItem(0, true)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        result?.contents?.also { url ->
            var parsable = true
            try {
                Uri.parse(url)
            } catch (_: Exception) {
                parsable = false
            }
            if (parsable) {
                val uri = Uri.parse(url)
                if (uri.path == "/app/roomparty") {
                    try {
                        GsonBuilder().create().fromJson(
                            Uri.decode(uri.encodedFragment!!),
                            AttendeeConFavorite::class.java
                        )
                    } catch (e: Throwable) {
                        logException(e)
                        longToast(getString(R.string.error_broken_invite))
                        return
                    }
                    startActivity(
                        Intent(
                            Intent.ACTION_SEND,
                            uri,
                            this,
                            RoomPartyPreviewerActivity::class.java
                        ).apply {
                            putExtra("notQr", false)
                        })
                } else
                    unrecognizedQrScan(url)
            } else
                unrecognizedQrScan(url)
        }
    }
    private fun unrecognizedQrScan(url: String) {
        AlertDialog.Builder(this)
            .setTitle(R.string.this_was_not_a_room_party)
            .setMessage(url)
            .setPositiveButton(R.string.copy_to_clipboard) { dialog, _ ->
                toClipboard(url, "qrcode", true)
                dialog.dismiss()
            }
            .setNegativeButton(R.string.dialog_cancel) { dialog, _ ->
                dialog.dismiss()
            }
            .create()
            .show()
    }
}
