package com.wasu.widgets.focuswidget;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.GridView;

import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.ChannelFlavor;

/**
 * Created by frewen on 2017/1/4.
 * 继承GridView.解决GridView中在 SDK=19的Android系统会抢焦点的问题
 */

public class CustomGridView extends GridView {
    private static final String TAG = "CustomGridView";
    private GridViewColumnEndListener mGridViewColumnEndListener;

    public CustomGridView(Context context) {
        super(context);
    }

    public CustomGridView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
    }


    @Override
    public boolean isInTouchMode() {
        if (19 <= Build.VERSION.SDK_INT) {
            return !(hasFocus() && !super.isInTouchMode());
        } else {
            return super.isInTouchMode();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //针对乐视的渠道进行焦点的特殊处理
        if (BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.LETV_MARKET) && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (0 == ((getSelectedItemPosition() + 1) % getNumColumns()) && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
                if (null != mGridViewColumnEndListener) {
                    mGridViewColumnEndListener.onColumnEnd();
                    return true;
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public interface GridViewColumnEndListener {
        void onColumnEnd();
    }

    public void setOnGridViewColumnEndListener(GridViewColumnEndListener listener){
        this.mGridViewColumnEndListener = listener;
    }
}
