package com.bernard.mcqinator.view.activities.fragenActivities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

import com.bernard.mcqinator.api.fragen.Frage;

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

/**
 * @author samy
 * @date on 04/05/17.
 */

public abstract class FrageActivity<T extends Frage> extends Activity {

    public static final String FRAGEN = "com.bernard.qcminator.FRAGEN";
    public static final String REPLIES = "com.bernard.qcminator.REPLIES";
    public static final String QUIZ_DATA = "com.bernard.qcminator.QUIZ_DATA";

    List<T> fragen;
    private List<Frage.Reply> replies;
    private int currentFrage = 0;
    public abstract void initiate(T f);

    @Override
    @SuppressWarnings("unchecked")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Parcelable[] preFragen = getIntent().getParcelableArrayExtra(FRAGEN);
        fragen = new ArrayList<>();
        for (Parcelable aPreFragen : preFragen) fragen.add((T) aPreFragen);
        Log.v("FrageActivity","Fragen : "+fragen);
        replies = new ArrayList<>();
        final View rout = findViewById(android.R.id.content);
        rout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                initiate(fragen.get(currentFrage));
                rout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    public void reply(Frage.Reply reply){
        replies.add(reply);

        currentFrage++;
        if(currentFrage == fragen.size()) {
            Intent i = new Intent();
            i.putParcelableArrayListExtra(REPLIES,(ArrayList<? extends Parcelable>)replies);
            setResult(RESULT_OK,i);
            finish();
            return;
        }
        initiate(fragen.get(currentFrage));
    }


}
