package com.yidian.shenghuoquan.newscontent.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.CompoundButton
import androidx.constraintlayout.widget.ConstraintLayout
import com.yidian.common.AppConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.databinding.ViewPrivacyAgreementBinding
import com.yidian.shenghuoquan.newscontent.ui.ProtocolActivity
import com.yidian.xpage.XPageManager

/**
 * author: yinjiacheng
 * date: 6/24/21 3:32 AM
 * description: 用户协议、隐私政策
 */
class PrivacyAgreementView @JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null,
  defStyle: Int = 0
) : ConstraintLayout(context, attrs, defStyle), View.OnClickListener, CompoundButton.OnCheckedChangeListener {

  private val viewBinding: ViewPrivacyAgreementBinding =
    ViewPrivacyAgreementBinding.bind(
      View.inflate(
        getContext(),
        R.layout.view_privacy_agreement,
        this
      )
    )

  private var callback: OnPrivacyAgreementCallback? = null

  init {
    viewBinding.tvPrivacyPolicy.setOnClickListener(this)
    viewBinding.tvUserAgreement.setOnClickListener(this)
    viewBinding.cbAgree.setOnCheckedChangeListener(this)
  }

  override fun onClick(v: View?) {
    val id = v?.id
    if (id == R.id.tv_privacy_policy) {
      // 隐私政策
      val map = HashMap<String, String>()
      map[ProtocolActivity.ProtocolTitleKey] = resources.getString(R.string.privacy_policy_statement)
      map[ProtocolActivity.ProtocolUrlKey] = AppConfig.privacyPolicyStatement
      XPageManager.push(XRouterPathConstants.PROTOCOL, map)
    } else if (id == R.id.tv_user_agreement) {
      // 用户协议
      val map = HashMap<String, String>()
      map[ProtocolActivity.ProtocolTitleKey] = resources.getString(R.string.user_protocol)
      map[ProtocolActivity.ProtocolUrlKey] = AppConfig.userProtocol
      XPageManager.push(XRouterPathConstants.PROTOCOL, map)
    }
  }

  /**
   * 获取当前是否选中
   */
  fun getCheckState(): Boolean {
    return viewBinding.cbAgree.isChecked
  }

  override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
    if (buttonView?.isPressed == false) return
    callback?.onCheckPrivacyAgreement(isChecked)
  }

  fun setOnPrivacyAgreementCallback(callback: OnPrivacyAgreementCallback) {
    this.callback = callback
  }

  interface OnPrivacyAgreementCallback {
    /**
     * 选择用户协议和隐私政策
     */
    fun onCheckPrivacyAgreement(isCheck: Boolean)
  }
}
