/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * 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.
 */
package com.android.launcher3.accessibility

import android.view.View
import android.view.ViewGroup
import com.android.launcher3.CellLayout
import com.android.launcher3.DropTarget.DragObject
import com.android.launcher3.dragndrop.DragController
import com.android.launcher3.dragndrop.DragOptions
import com.android.launcher3.views.ActivityContext
import java.util.function.Function

/**
 * Utility listener to enable/disable accessibility drag flags for a ViewGroup containing
 * CellLayouts
 */
open class AccessibleDragListenerAdapter
/**
 * @param parent the viewgroup containing all the children
 * @param delegateFactory function to create no delegates
 */
(
    private val mViewGroup: ViewGroup,
    private val mDelegateFactory: Function<CellLayout, DragAndDropAccessibilityDelegate>
) : DragController.DragListener, ViewGroup.OnHierarchyChangeListener {
    override fun onDragStart(dragObject: DragObject, options: DragOptions) {
        mViewGroup.setOnHierarchyChangeListener(this)
        enableAccessibleDrag(true, dragObject)
    }

    override fun onDragEnd() {
        mViewGroup.setOnHierarchyChangeListener(null)
        enableAccessibleDrag(false, null)
        val activityContext = ActivityContext.lookupContext(mViewGroup.context) as ActivityContext
        activityContext.getDragController<DragController<*>>()?.removeDragListener(this)
    }

    override fun onChildViewAdded(parent: View, child: View) {
        if (parent === mViewGroup) {
            setEnableForLayout(child as CellLayout, true)
        }
    }

    override fun onChildViewRemoved(parent: View, child: View) {
        if (parent === mViewGroup) {
            setEnableForLayout(child as CellLayout, false)
        }
    }

    protected open fun enableAccessibleDrag(enable: Boolean, dragObject: DragObject?) {
        for (i in 0 until mViewGroup.childCount) {
            setEnableForLayout(mViewGroup.getChildAt(i) as CellLayout, enable)
        }
    }

    protected fun setEnableForLayout(layout: CellLayout, enable: Boolean) {
        layout.setDragAndDropAccessibilityDelegate(
            if (enable) mDelegateFactory.apply(layout) else null
        )
    }
}
