package com.zepchat.app.adapters;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.zepchat.app.MainActivity;
import com.zepchat.app.R;
import com.zepchat.core.data.User;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Ziver on 2014-11-06.
 */
public class UserListAdapter extends ArrayAdapter<User> {
    private HashMap<Object, Integer> mIdMap = new HashMap<Object, Integer>();
    private List<User> users;

    public UserListAdapter(Context context, List users) {
        super(context, android.R.layout.simple_list_item_1, users);
        this.users = users;
        for (int i = 0; i < users.size(); ++i) {
            mIdMap.put(users.get(i), i);
        }
    }

    @Override
    public void add(User user){
        if(user != null) {
            mIdMap.put(user, users.size());
            super.add(user);
        }
    }

    @Override
    public long getItemId(int position) {
        Object item = getItem(position);
        return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.contact_list_item, parent, false);
        }
        if(MainActivity.getCore().getSession(users.get(position)).hasUnread())
            convertView.setBackgroundColor(Color.CYAN);
        else
            convertView.setBackgroundColor(Color.TRANSPARENT);

        TextView alias = (TextView) convertView.findViewById(R.id.alias);
        alias.setText(users.get(position).getAlias());

        TextView messageSum = (TextView) convertView.findViewById(R.id.messageSum);
        messageSum.setText(users.get(position).getPublicKey());

        return convertView;
    }
}
