package app.furmeet.events.system.schedule

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
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.system.AssetImageViewerActivity
import com.adlerosn.brasilfurfest.R
import app.furmeet.events.system.SplashActivity
import app.furmeet.events.system.TranslatableAppCompatActivity
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 app.furmeet.events.system.schedule.managers.ScheduleManager
import app.furmeet.events.system.schedule.managers.ScheduleManagerGetter
import com.adlerosn.brasilfurfest.databinding.ActivityScheduleBinding
import com.google.android.material.snackbar.Snackbar
import com.google.gson.GsonBuilder
import com.google.zxing.integration.android.IntentIntegrator
//import kotlinx.android.synthetic.main.activity_schedule.*
//import org.jetbrains.anko.longToast


class ScheduleActivity : TranslatableAppCompatActivity() {
    lateinit var binding: ActivityScheduleBinding
    private lateinit var scheduleManager: ScheduleManager
    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 = ScheduleManagerGetter[this]

        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 { view ->
            Intent(view.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 {
            Snackbar.make(it, R.string.schedule_events_favorites, Snackbar.LENGTH_LONG).apply {
                setActionTextColor(this@ScheduleActivity.getColorCompat(R.color.colorBase20))
                view.setBackgroundColor(this@ScheduleActivity.getColorCompat(R.color.colorBase03))
                show()
            }
            true
        }
    }


    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_developer -> {
                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
            }
            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()
    }

    override fun onBackPressed() {
        if (binding.tabs.selectedTabPosition == 0)
            super.onBackPressed()
        else
            binding.container.setCurrentItem(0, true)
    }

    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 ->
            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)
                })
            }
        }
    }
}
