package com.cr.widget

import android.content.Context
import android.graphics.BitmapFactory
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.cr.common.CrFileManager
import com.cr.cruav.R
import com.cr.data.CrUtil
import com.cr.view.CrIndicator
import java.io.FileInputStream
import java.io.FileNotFoundException

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/6/16 16:19
 * 描述：图片浏览器
 */
class CrImageBrowserWidget @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : CrConstraintLayoutWidget(context, attrs, defStyleAttr) {
    private var viewPager: ViewPager2? = null // define: 2023/6/16 页面滑动组件
    private var dataList: MutableList<String> = mutableListOf() // define: 2023/6/16 数据集合
    private var adapter: BaseAdapter? = null // define: 2023/6/16 适配器
    private var listener:iChangeListener?=null // define: 2023/6/17 对外接口
    private var wgIndicator:CrIndicator?= null // define: 2023/8/26 指示器

    // todo: 2023/6/17 对外接口
    interface iChangeListener{
        fun onChange(file:ImageFileModel?)
    }

    /**
     * 初始化
     */
    init {
        initView(R.layout.wg_image_browser)
        joinControls()
    }

    /**
     * 挂载控件
     */
    override fun joinControls() {
        super.joinControls()
        // todo: 2023/6/16 挂载视图控件
        viewPager = findViewById(R.id.wg_pager)
        // todo: 2023/8/26 挂载指示图控件
        wgIndicator = findViewById(R.id.wg_indicator)
        // todo: 2023/6/16 设置适配器
        adapter = BaseAdapter(dataList)
        viewPager?.adapter = adapter
        // todo: 2023/6/17 设置监听 此处设置监听会导致空引用 后期处理
//        viewPager?.registerOnPageChangeCallback(pageChangeListener)
    }

    /**
     * 页面滑动监听
     */
    private var pageChangeListener = object:OnPageChangeCallback(){
        // todo: 2023/6/17 选择页面
        override fun onPageSelected(position: Int) {
            var fileModel = adapter?.crGetSelectItem(position)
            if(fileModel != null){
                if(listener != null) listener?.onChange(fileModel)
            }
            // todo: 2023/8/26 设置指示器
            wgIndicator?.crSetIndex(position)
        }
    }

    /**
     * 适配器
     * @property dataList List<String>?
     * @constructor
     */
    internal class BaseAdapter(dataList: MutableList<String>) :
        RecyclerView.Adapter<BaseAdapter.BaseViewHolder?>() {
        private var dataList: MutableList<String>? = mutableListOf() // define: 2023/6/16 数据集合
        private var fileList:MutableList<ImageFileModel>?= mutableListOf()  // define: 2023/6/17 文件集合
        // todo: 2023/6/16 创建视图
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BaseAdapter.BaseViewHolder {
            var itemView: View =
                LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false)
            return BaseViewHolder(itemView)
        }

        // todo: 2023/6/16 绑定视图
        override fun onBindViewHolder(holder: BaseAdapter.BaseViewHolder, position: Int) {
            var imagePath = this.dataList!![position]
            try {
                var fis = FileInputStream(imagePath)
                var bitmap = BitmapFactory.decodeStream(fis)
                holder.imageView?.setImageBitmap(bitmap)
            } catch (ex: FileNotFoundException) {
                CrUtil.print("加载图片错误：" + ex.message)
            }
        }

        // todo: 2023/6/16 返回视图数量
        override fun getItemCount(): Int {
            return dataList!!.size
        }

        inner class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var imageView: ImageView? = null  // define: 2023/6/16 图片展示控件

            /**
             * 初始化
             */
            init {
                imageView = itemView.findViewById(R.id.item_img_image)
            }
        }

        /**
         * 初始化
         */
        init {
            this.dataList = dataList
            initFileList()
        }

        /**
         * 文件初始化
         */
        private fun initFileList(){
            this.fileList?.let {
                it.clear()
                for(filePath in this.dataList!!){
                    var model = ImageFileModel(filePath)
                    it.add(model)
                }
            }
        }

        /**
         * 更新数据
         * @param dataList List<String>
         */
        fun crUpdate(dataList: MutableList<String>) {
            this.dataList = dataList
            initFileList()
            notifyDataSetChanged()
        }

        /**
         * 返回当前位置的文件模型
         * @param position Int 位置
         * @return ImageFileModel? 信息
         */
        fun crGetSelectItem(position:Int):ImageFileModel?{
            return this.fileList?.get(position)
        }

    }

    // todo: 2023/6/17 照片模型
    class ImageFileModel {
        var fileName: String? = null // define: 2023/6/17 图片名称
        var fileSize: Long? = 0 // define: 2023/6/17 图片大小
        var fileSizeDescription: String? = null // define: 2023/6/17 图片大小描述
        var fileFullPath: String? = null  // define: 2023/6/17 文件路径

        /**
         * 初始化
         * @param filePth String 文件路径
         * @constructor
         */
        constructor(filePth: String) {
            this.fileFullPath = filePth
            this.fileName = CrFileManager.getFileName(filePth)
            this.fileSize = CrFileManager.getFileSize(filePth)
            this.fileSizeDescription = CrFileManager.fileSizeToString(this.fileSize!!)
        }
    }

    /**
     * 初始化
     */
    fun crInit(){
        this.dataList.clear()
        adapter?.crUpdate(this.dataList)
        viewPager?.unregisterOnPageChangeCallback(pageChangeListener)
    }

    /**
     * 添加图片
     * @param imagePath String 图片路径
     */
    fun crAppendImage(imagePath: String) {
        this.dataList.add(imagePath)
        wgIndicator?.crSetCount(dataList.size)
        adapter?.crUpdate(this.dataList)
        // todo: 2023/6/17 追加了一条数据后注册监听
        if(this.dataList.size == 1){
            viewPager?.registerOnPageChangeCallback(pageChangeListener)
        }
        viewPager?.currentItem = this.dataList.size-1
    }

    /**
     * 设置监听
     * @param listener iChangeListener 监听
     */
    fun crSetListener(listener:iChangeListener){
        this.listener = listener
    }
}