/*
 * Copyright (C) 2017  YangBin
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package tech.summerly.quiet.module.common.view

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import kotlinx.android.synthetic.main.common_view_load_state.view.*
import tech.summerly.quiet.R

/**
 * author : yangbin10
 * date   : 2017/11/17
 * 放在需要加载数据的view上,提供一个加载的动画和加载失败的重试按钮
 */
class LoadStateView : FrameLayout {

    private val root: View

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        @SuppressLint("InflateParams")
        root = LayoutInflater.from(context).inflate(R.layout.common_view_load_state, null, false)
        root.setOnTouchListener { _, _ ->
            //拦截触摸事件..
            true
        }
        addView(root, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
    }

    var loadingText: String = "载入中..."

    var failedText: String = "载入失败,点击重试."

    private var onRetryClickListener: View.OnClickListener? = null


    fun setLoading() {
        visibility = View.VISIBLE
        progressBar.visibility = View.VISIBLE
        imageStateIndicator.visibility = View.GONE
        textHint.text = loadingText
    }

    fun setLoadFailed() {
        visibility = View.VISIBLE
        progressBar.visibility = View.GONE
        imageStateIndicator.visibility = View.VISIBLE
        imageStateIndicator.setImageResource(R.drawable.ic_error_outline_black_24dp)
        textHint.text = failedText
        textHint.setOnClickListener {
            textHint.setOnClickListener(null)
            textHint.isClickable = false
            onRetryClickListener?.onClick(it)
        }
    }

    fun hide() {
        visibility = View.GONE
    }

    fun setRetryClickListener(listener: View.OnClickListener) {
        onRetryClickListener = listener
    }

}