package com.atmob.keyboard_android.component.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.atmob.keyboard_android.component.widget.lifecycle.LifecycleViewGroup;

/**
 * 可以自定义绘制顺序的FrameLayout
 */
public class CustomOrderFrameLayout extends LifecycleViewGroup {
    // 置顶的View索引
    private int frontIndex = -1;
    // 置底的View索引
    private int backIndex = -1;

    public CustomOrderFrameLayout(@NonNull Context context) {
        this(context, null);
    }

    public CustomOrderFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomOrderFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 启用自定义绘制顺序
        setChildrenDrawingOrderEnabled(true);
    }

    /**
     * 将指定View置顶
     */
    @Override
    public void bringChildToFront(View child) {
        int index = indexOfChild(child);
        if (index != -1) {
            frontIndex = index;
            // 清除置底标记
            backIndex = -1;
            // 触发重绘
            invalidate();
        }
    }

    /**
     * 将指定View置底
     */
    public void sendChildToBack(View child) {
        int index = indexOfChild(child);
        if (index != -1) {
            backIndex = index;
            // 清除置顶标记
            frontIndex = -1;
            invalidate();
        }
    }

    @Override
    protected int getChildDrawingOrder(int childCount, int i) {
        // 处理置顶逻辑
        if (frontIndex != -1) {
            if (i == childCount - 1) {
                // 最后绘制置顶View
                return frontIndex;
            } else if (i >= frontIndex) {
                // 调整其他View顺序
                return i + 1;
            }
        }

        // 处理置底逻辑
        if (backIndex != -1) {
            // 最先绘制置底View
            if (i == 0) {
                return backIndex;
            } else if (i <= backIndex) {
                // 调整其他View顺序
                return i - 1;
            }
        }

        return super.getChildDrawingOrder(childCount, i);
    }
}
