package edu.whut.jianshu.Activity

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import edu.whut.jianshu.Adapter.PerceptionAdapter
import edu.whut.jianshu.Data.entity.Perception_bmob
import edu.whut.jianshu.Data.vo.Perception
import edu.whut.jianshu.R
import kotlinx.android.synthetic.main.activity_my_post.*

class MyPostActivity : AppCompatActivity() {
    private val perceptionList = ArrayList<Perception>()
    private lateinit var userId: String
    private lateinit var adapter: PerceptionAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_post)
        userId = getSharedPreferences("userinf", Context.MODE_PRIVATE).getString("user_id", "").orEmpty()
        initRecyclerView()
        loadPosts()
        mypost_back.setOnClickListener {
            finish()
        }
    }

    private fun initRecyclerView() {
        myPost_recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = PerceptionAdapter(perceptionList)
        myPost_recyclerView.adapter = adapter
    }

    private fun loadPosts() {
        val bmobQuery = BmobQuery<Perception_bmob>()
        bmobQuery.findObjects(object : FindListener<Perception_bmob>() {
            override fun done(list: List<Perception_bmob>, e: BmobException?) {
                if (e == null) {
                    for (item in list) {
                        if (item.userid == userId) {
                            perceptionList.add(Perception(item.objectId))
                        }
                    }
                    adapter.notifyDataSetChanged()
                } else {
                    Log.e("BmobQuery", "Error: ${e.message}", e)
                }
            }
        })
    }
}
