package app.furmeet.events.brasilfurfest.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.brasilfurfest.AssetImageViewerActivity
import com.adlerosn.brasilfurfest.R
import app.furmeet.events.brasilfurfest.SplashActivity
import app.furmeet.events.brasilfurfest.TranslatableAppCompatActivity
import app.furmeet.events.brasilfurfest.developer.DeveloperActivity
import app.furmeet.events.brasilfurfest.helper.*
import app.furmeet.events.brasilfurfest.schedule.abstractDataTypes.managed.AttendeeConFavorite
import app.furmeet.events.brasilfurfest.schedule.adapters.DaysPagerAdapter
import app.furmeet.events.brasilfurfest.schedule.adapters.LanguageSelectorListAdapter
import app.furmeet.events.brasilfurfest.schedule.managers.ScheduleManager
import app.furmeet.events.brasilfurfest.schedule.managers.ScheduleManagerGetter
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() {
    private lateinit var scheduleManager: ScheduleManager
    private lateinit var pagerAdapter: FragmentPagerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        ActivitiesForFragments[this.javaClass.simpleName] = this
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_schedule)
        setSupportActionBar(toolbar)
        resourcesAliased = this.resources
        scheduleManager = ScheduleManagerGetter[this]

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

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

        container.offscreenPageLimit = pagerAdapter.count

        fab.setOnClickListener {
            Intent(this, FavoritesActivity::class.java).apply {
                startActivity(this)
            }
        }
        fab.isLongClickable = true
        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)
                    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 (tabs.selectedTabPosition == 0)
            super.onBackPressed()
        else
            container.setCurrentItem(0, true)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        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)
                })
            }
        }
    }
}
