package godau.fynn.dsbdirect.activity

// Created by Jasper Michalke <jasper.michalke@jasmich.de> under license EUPL 1.2.

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import android.view.View
import android.widget.ListView
import android.widget.TextView
import godau.fynn.dsbdirect.Login
import godau.fynn.dsbdirect.R
import godau.fynn.dsbdirect.Utility
import godau.fynn.dsbdirect.ZoomImage
import godau.fynn.dsbdirect.manager.DownloadManager
import godau.fynn.dsbdirect.manager.LoginManager
import godau.fynn.dsbdirect.table.NoticeAdapter


class NoticeBoardActivity : AppCompatActivity() {

    private lateinit var noticeAdapter: NoticeAdapter
    private lateinit var login: Login

    companion object {
        const val EXTRA_CONTENT_INFORMATION = "content"
        @JvmStatic var lastZoomedImage: ZoomImage? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notice_board)

        val u = Utility(this)
        u.stylize()

        val mLoginManager = LoginManager(this)

        login = mLoginManager.activeLogin
        // Start loading
        Thread(Runnable { loadNotices() }).start()

        val toolbar: Toolbar = findViewById<Toolbar>(R.id.toolbar)
        toolbar.setBackgroundColor(u.colorPrimary)
        setSupportActionBar(toolbar)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
    }

    private fun loadNotices() {
        var dManager = DownloadManager(this)

        var content: DownloadManager.ContentInformation
        if (intent.hasExtra(EXTRA_CONTENT_INFORMATION)) {
            content = intent.getSerializableExtra(EXTRA_CONTENT_INFORMATION) as DownloadManager.ContentInformation
        } else {
            content = dManager.downloadContentInformation(login)
        }

        runOnUiThread {
            val listView = findViewById<ListView>(R.id.table)
            if (::noticeAdapter.isInitialized) {
                noticeAdapter.addAll(content.notices)
            } else {
                noticeAdapter = NoticeAdapter(this, content.notices, findViewById(R.id.contentCoordinator))
                listView.adapter = noticeAdapter
            }
            listView.visibility = View.VISIBLE
            findViewById<TextView>(R.id.text).visibility = View.GONE
        }
    }

    override fun onBackPressed() {
        if (lastZoomedImage != null && lastZoomedImage!!.zoomed) {
            lastZoomedImage!!.zoomOut();
        } else
            super.onBackPressed()
    }
}