package com.develop.common.widget

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.blankj.utilcode.util.KeyboardUtils
import com.develop.common.R

import com.develop.common.databinding.HomeSortFilterSearchViewBinding


class HomeFilterSortSearchView : RelativeLayout {
    private var binding: HomeSortFilterSearchViewBinding

    var onFunctionCallback: OnFunctionCallback? = null

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    init {
        val root = View.inflate(context, R.layout.home_sort_filter_search_view, this)
        binding = HomeSortFilterSearchViewBinding.bind(root)
        binding.searchCardView.setOnClickListener {
            binding.cardLayout.visibility = View.GONE
            binding.searchLayout.visibility = View.VISIBLE
            onFunctionCallback?.onSearchClick()
        }
        binding.filterCardView.setOnClickListener {
            onFunctionCallback?.onFilterClick(binding.filterCardView)
        }
        binding.sortCardView.setOnClickListener {
            onFunctionCallback?.onSortClick(binding.sortCardView)
        }
        binding.ivSearch.setOnClickListener {
            KeyboardUtils.hideSoftInput(context as Activity)
            val content = binding.etSearch.text.toString()
            if (content.isNotEmpty()) {
                onFunctionCallback?.onInputSearch(content)
            }
        }
        binding.downloadLayout.setOnClickListener {
            onFunctionCallback?.onDownloadClick()
        }

        binding.onlineLayout.setOnClickListener {
            onFunctionCallback?.onOnlineRecipesClick()
        }
    }

    fun resetView() {
        binding.cardLayout.visibility = View.VISIBLE
        binding.searchLayout.visibility = View.GONE
    }

    interface OnFunctionCallback {
        fun onFilterClick(filterView: View)
        fun onSortClick(sortView: View)
        fun onSearchClick()
        fun onInputSearch(searchContent: String)
        fun onDownloadClick()
        fun onOnlineRecipesClick()
    }

    fun updateFilterName(filterName: String) {
        binding.tvFilterName.text = filterName
    }

    fun updateSortName(sortName: String) {
        binding.tvSortName.text = sortName
    }

    fun updateHotWord(hotWord: String) {
        binding.etSearch.setText(hotWord)
    }

    fun hideOnlineLayout(isOnLineState: Boolean) {
        if (isOnLineState) {
            binding.onlineLayout.visibility = View.INVISIBLE
        } else {
            binding.onlineLayout.visibility = View.VISIBLE
        }
    }

    fun getOnlineLayoutVisible(): Boolean {
        return binding.onlineLayout.visibility == View.VISIBLE
    }
}

