package com.android.chmo.ui.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.chmo.R;
import com.android.chmo.utils.CommonUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/30.
 */

public class TopBar extends RelativeLayout {
    @BindView(R.id.back)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView  titleView;
    @BindView(R.id.right)
    TextView  rightView;
    @BindView(R.id.border)
    View      border;

    private String  title    = "";
    private boolean showBack = true;
    private int     background;
    private boolean showBorder;
    private int     style;

    public TopBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
        if (typedArray != null) {
            title = typedArray.getString(R.styleable.TopBar_topTitle);
            showBack = typedArray.getBoolean(R.styleable.TopBar_showBack, true);
            showBorder = typedArray.getBoolean(R.styleable.TopBar_showBorder, false);
            style = typedArray.getInt(R.styleable.TopBar_style, 1);
            typedArray.recycle();
        }

        int[] attrsArray = new int[]{
                android.R.attr.background
        };
        TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
        if (ta != null) {
            background = ta.getColor(0, Color.rgb(242, 244, 245));
            ta.recycle();
        }
        init(context);
    }


    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.top_bar, this);
        ButterKnife.bind(this);
        if (style == 0) {
            backBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.icon_back_white));
            titleView.setTextColor(Color.WHITE);
            rightView.setTextColor(Color.WHITE);
        }
        backBtn.setVisibility(showBack ? View.VISIBLE : View.GONE);
        titleView.setText(title);
        setPadding(0, CommonUtils.getStatusBarHeight(context), 0, 0);
        setBackgroundColor(background);
        border.setVisibility(showBorder ? VISIBLE : GONE);
    }

    @OnClick(R.id.back)
    void onClick() {
        Activity activity = (Activity) getContext();
        activity.finish();
    }


    public void setTitle(String title) {
        this.title = title;
        titleView.setText(title);
    }

    public void setRightBtn(String text, OnClickListener listener) {
        rightView.setText(text);
        rightView.setVisibility(View.VISIBLE);
        rightView.setOnClickListener(listener);
    }

}
