package com.android.chmo.ui.view;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * 多页面 索引
 */
public class PageIndexView extends LinearLayout{
    private int totalCount;

    private int curIndex;

    private int defDrawable = -1;
    private int selectedDrawable = -1;


    public PageIndexView(Context context) {
        super(context);
        init();
    }
    public PageIndexView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
    }

    public void setCount(int count) {
        totalCount = count;
        initView();
    }

    public void setCurIndex(int index) {
        curIndex = index;
        refreshView();
    }

    public void setDefDrawable(int resId) {
        defDrawable = resId;
    }

    public void setSelectedIndexDrawable(int resId) {
        selectedDrawable = resId;
    }

    private void initView() {
        removeAllViews();
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 8;
        lp.rightMargin = 8;
        for (int i=0; i < totalCount; i++) {
            ImageView item = new ImageView(getContext());
            addView(item, lp);
        }
    }

    private void refreshView() {
        if (-1 == selectedDrawable || -1 == defDrawable) {
            return;
        }
        ImageView item = null;
        for (int i=0; i < getChildCount(); i++) {
            item = (ImageView) getChildAt(i);
            if (i == curIndex) {
                item.setImageDrawable(ContextCompat.getDrawable(getContext(),selectedDrawable));
            } else {
                item.setImageDrawable(ContextCompat.getDrawable(getContext(),defDrawable));
            }
        }
    }
}
