package com.bernard.mcqinator.view;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bernard.mcqinator.R;
import com.bernard.mcqinator.api.QuizMetadata;

import java.util.List;

/**
 * @author Mysaa
 * @date on 17/04/17.
 */

public class QuizAdapter extends BaseAdapter {

    private final List<QuizMetadata> items;
    private final Context ctx;

    public QuizAdapter(List<QuizMetadata> quizz,Context context){
        this.items = quizz;
        this.ctx = context;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public QuizMetadata getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 42;//Use is up to the developer
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View mainView;
        if(convertView != null)
            mainView = convertView;
        else
            mainView = LayoutInflater.from(ctx).inflate(R.layout.quiz_row_layout,parent,false);

        TextView nameText;
        TextView authorText;
        ImageView iconView;

        try {
            nameText = mainView.findViewById(R.id.quizAdapterName);
            authorText = mainView.findViewById(R.id.quizAdapterAuthor);
            iconView = mainView.findViewById(R.id.quizAdapterIcon);

            if (nameText == null)
                throw new RuntimeException("Failed to find view with ID quizAdapterName in layout");
            if (authorText == null)
                throw new RuntimeException("Failed to find view with ID quizAdapterAuthor in layout");
            if (iconView == null)
                throw new RuntimeException("Failed to find view with ID quizAdapterIcon in layout");

        } catch (ClassCastException e) {
            Log.e("QuizAdapter", "Id quizAdapterName and quizAdapterAuthor must be a TextView and quizAdapterIcon must be an ImageView");
            throw new IllegalStateException("QuizAdapter'layout ids didn't match the right types", e);
        }

        final QuizMetadata quiz = getItem(position);
        if(quiz != null) {
            nameText.setText(quiz.getName());
            authorText.setText(quiz.getAuthor());
            iconView.setImageDrawable(ContextCompat.getDrawable(ctx,quiz.getType().getQuizIconID()));
        }
        return mainView;
    }
}
