package tech.shadowfox.shadow.android.view.widgets

import android.content.Context
import android.content.res.TypedArray
import android.support.v4.widget.NestedScrollView
import android.util.AttributeSet
import android.view.View
import tech.shadowfox.shadow.R
import tech.shadowfox.shadow.android.utils.use

/**
 * Copyright 2017 Camaron Crowe
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
class WrappedNestedScrollView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : NestedScrollView(context, attrs, defStyleAttr) {

    var maxWrapHeight = 0
        set(value) {
            if (value != field) {
                field = value
                requestLayout()
            }
        }

    init {
        context.theme.obtainStyledAttributes(attrs, R.styleable.WrapNestedScrollView, defStyleAttr, 0).use {
            readAttributes(it)
        }
    }

    private fun readAttributes(typedArray: TypedArray) {
        maxWrapHeight = typedArray.getDimensionPixelSize(R.styleable.WrapNestedScrollView_maxWrapHeight, 0)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var heightSpec = heightMeasureSpec
        if (maxWrapHeight > 0) {
            val hSize = View.MeasureSpec.getSize(heightMeasureSpec)
            val hMode = View.MeasureSpec.getMode(heightMeasureSpec)

            heightSpec = when (hMode) {
                View.MeasureSpec.AT_MOST -> View.MeasureSpec.makeMeasureSpec(Math.min(hSize, maxWrapHeight), View.MeasureSpec.AT_MOST)
                View.MeasureSpec.UNSPECIFIED -> View.MeasureSpec.makeMeasureSpec(maxWrapHeight, View.MeasureSpec.AT_MOST)
                View.MeasureSpec.EXACTLY -> View.MeasureSpec.makeMeasureSpec(Math.min(hSize, maxWrapHeight), View.MeasureSpec.EXACTLY)
                else -> error("Invalid MeasureSpec")
            }
        }

        super.onMeasure(widthMeasureSpec, heightSpec)
    }
}