package de.tudarmstadt.informatik.hostage.ui2.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import de.tudarmstadt.informatik.hostage.R;
import de.tudarmstadt.informatik.hostage.ui2.model.PlotComparisonItem;

/**
 * Created by Julien on 22.02.14.
 */
public class StatisticListAdapter extends ArrayAdapter<PlotComparisonItem> {
    private class ViewHolder {
        public TextView titleView;
        public TextView valueView;
        public TextView colorView;
    }

    public interface ValueFormatter {
        public String convertValueToString(double value);
    }

    private ValueFormatter formatter;
    private final Context context;
    private List<PlotComparisonItem> values;

    public void setValueFormatter(ValueFormatter formatter){
        this.formatter = formatter;
    }

    public StatisticListAdapter(Context context, List<PlotComparisonItem> objects) {
        super(context, getLayoutID(), objects);
        List<PlotComparisonItem> list = objects == null ? new ArrayList<PlotComparisonItem>() : objects;
        this.context = context;
        this.values = list;
    }

    public void setValues(List<PlotComparisonItem> list){
        this.values = list;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = convertView;
        ViewHolder holder = null;

        final PlotComparisonItem item = values.get(position);

        if(rowView == null){
            rowView = inflater.inflate(getLayoutID() , parent, false);
            holder = new ViewHolder();
            holder.titleView = (TextView) rowView.findViewById(R.id.title_text_view);
            holder.valueView = (TextView) rowView.findViewById(R.id.value_text_view);
            holder.colorView = (TextView) rowView.findViewById(R.id.color_view);
            rowView.setTag(holder);
        } else {
            holder = (ViewHolder) rowView.getTag();
        }


        this.configureView(holder, item);

        return rowView;
    }

    static public int getLayoutID(){
        return R.layout.plot_list_item;
    }

    private void configureView(ViewHolder holder, PlotComparisonItem item){
        holder.colorView.setBackgroundColor(item.getColor());
        holder.titleView.setText(item.getTitle());

        if (this.formatter == null){
            holder.valueView.setText("" + item.getValue2());
        } else {
            holder.valueView.setText(this.formatter.convertValueToString(item.getValue2()));
        }
    }
}
