package edu.whut.jianshu.Fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import edu.whut.jianshu.R

class BookPageFragment : Fragment() {
    private var bookContent: String? = null
    private var pageIndex: Int = 0

    companion object {
        private const val ARG_BOOK_CONTENT = "book_content"
        private const val ARG_PAGE_INDEX = "page_index"

        fun newInstance(bookContent: String, pageIndex: Int): BookPageFragment {
            return BookPageFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_BOOK_CONTENT, bookContent)
                    putInt(ARG_PAGE_INDEX, pageIndex)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            bookContent = it.getString(ARG_BOOK_CONTENT)
            pageIndex = it.getInt(ARG_PAGE_INDEX)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_content, container, false)
        val textViewContent: TextView = view.findViewById(R.id.textViewContent)

        // 计算当前页的内容
        val startIndex = pageIndex * (10 * 100)
        val endIndex = minOf((pageIndex + 1) * (10 * 100), bookContent?.length ?: 0)
        val currentPageContent = bookContent?.substring(startIndex, endIndex) ?: ""
        textViewContent.text = currentPageContent

        return view
    }
}
