package com.zjgsu.jianshu

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import cn.bmob.v3.Bmob
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import com.zjgsu.jianshu.Adapter.BookAdapter2
import com.zjgsu.jianshu.Bmob.Book_bmob
import kotlinx.android.synthetic.main.activity_categorypage.*
import kotlinx.android.synthetic.main.layout_bottom_navigation.*

class LiteratureActivity : AppCompatActivity() {
    private lateinit var adapter: BookAdapter2
    private var bookList = ArrayList<Book>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_categorypage)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.menu)
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754")
        val titleTextView = findViewById<TextView>(R.id.categoryPage_title)
        titleTextView.text = "文学"
        adapter = BookAdapter2(bookList,1)
        categoryPage_recyclerView.layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        categoryPage_recyclerView.adapter = adapter
        categoryPage_swipeRefresh.setOnRefreshListener {
            loadBooks()    //下拉刷新
        }
        setupNavigation()
        loadBooks()
        setupBottomNavigation()
        returnToBookcity()

    }

    private fun setupNavigation() {     //侧边栏
        categoryPage_navView.setCheckedItem(R.id.literature)
        categoryPage_navView.setNavigationItemSelectedListener { menuItem ->
            startActivity(Intent(this, when (menuItem.itemId) {
                R.id.literature -> LiteratureActivity::class.java
                R.id.management -> ManagementActivity::class.java
                R.id.psychology -> PsychologyActivity::class.java
                R.id.science -> ScienceActivity::class.java
                R.id.philosophy -> PhilosophyActivity::class.java
                else -> MainActivity::class.java
            }))
            categoryPage_drawerLayout.closeDrawers()
            true
        }
    }

    private fun loadBooks() {
        val query = BmobQuery<Book_bmob>()
        query.addWhereEqualTo("category_id", 1)
        query.findObjects(object : FindListener<Book_bmob>() {
            override fun done(list: List<Book_bmob>?, e: BmobException?) {
                categoryPage_swipeRefresh.isRefreshing = false
                if (e == null && list != null) {
                    updateBookList(list)
                } else {
                    Log.e("LiteratureActivity", "Error refreshing books: ${e?.message}", e)
                    Toast.makeText(this@LiteratureActivity, "Failed to refresh books.", Toast.LENGTH_SHORT).show()
                }
            }
        })
    }

    private fun updateBookList(list: List<Book_bmob>) {
        bookList.clear()
        bookList.addAll(list.map { Book(it.name, it.introduce, it.picture.url) })
        adapter.notifyDataSetChanged()
    }

    private fun setupBottomNavigation() {
        bookcity.setOnClickListener {
            finish()  // Simplify navigation logic
        }
        bookshelf.setOnClickListener {
            startActivity(Intent(this, BookShelfActivity::class.java))
        }
        reading_comprehension.setOnClickListener {
            startActivity(Intent(this, PerceptionActivity::class.java))
        }
        homepage.setOnClickListener {
            startActivity(Intent(this, MyActivity::class.java))
        }
    }
    private fun returnToBookcity(){
        categoryPage_back.setOnClickListener{
            startActivity(Intent(this, MainActivity::class.java))
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            categoryPage_drawerLayout.openDrawer(GravityCompat.START)
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}
