package de.hosenhasser.funktrainer.views;

import android.content.Context;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.Spanned;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.LinkedList;
import java.util.List;

import de.hosenhasser.funktrainer.R;
import de.hosenhasser.funktrainer.URLImageParser;
import de.hosenhasser.funktrainer.data.Question;
import de.hosenhasser.funktrainer.data.QuestionState;
import de.hosenhasser.funktrainer.data.Repository;

public class QuestionView extends LinearLayout {
    private boolean replaceNNBSP = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH;

    private RadioGroup radioGroup;
    private TextView questionTextView;
    private QuestionState questionState;
    private int listPosition;
    private Repository repository;

    public QuestionView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public QuestionView(Context context) {
        super(context);
        init();
    }

    public QuestionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        listPosition = -1;
        inflate(getContext(), R.layout.question, this);
        this.radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
        questionTextView = (TextView) findViewById(R.id.textViewQuestion);
        repository = new Repository(getContext());

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                questionState.setAnswer(getPositionOfButton(i));
            }
        });
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        QuestionViewSavedState ss = (QuestionViewSavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).restoreHierarchyState(ss.childrenStates);
        }
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        QuestionViewSavedState ss = new QuestionViewSavedState(superState);
        for (int i =0; i < getChildCount(); i++) {
            getChildAt(i).saveHierarchyState(ss.childrenStates);
        }
        return ss;
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
        dispatchThawSelfOnly(container);
    }

    private static class QuestionViewSavedState extends BaseSavedState {
        SparseArray childrenStates = new SparseArray<>();

        QuestionViewSavedState(Parcelable superState) {
            super(superState);
        }

        private QuestionViewSavedState(Parcel in, ClassLoader classLoader) {
            super(in);
            childrenStates = in.readSparseArray(classLoader);
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeSparseArray(childrenStates);
        }

        public static final ClassLoaderCreator<QuestionViewSavedState> CREATOR
                = new ClassLoaderCreator<QuestionViewSavedState>() {
            @Override
            public QuestionViewSavedState createFromParcel(Parcel in, ClassLoader loader) {
                return new QuestionViewSavedState(in, loader);
            }

            @Override
            public QuestionViewSavedState createFromParcel(Parcel in) {
                return createFromParcel(null);
            }

            public QuestionViewSavedState[] newArray(int size) {
                return new QuestionViewSavedState[size];
            }
        };
    }

    public void setListPosition(final int listPosition) {
        this.listPosition = listPosition;
    }

    public int getPositionOfButton(int id) {
        for (int i = 0; i < 4; i++) {
            if (radioGroup.getChildAt(i).getId() == id) return i;
        }
        return -1;
    }


    public void setRadioGroupEnabled(boolean enabled) {
        radioGroup.setEnabled(enabled);
        for (RadioButton b : getRadioButtons()) b.setEnabled(enabled);
    }

    public void setQuestionState(QuestionState qs) {
        this.questionState = qs;
        Question q = qs.getQuestion(repository);

        setQuestionText(q.getQuestion());

        final List<RadioButton> radioButtons = getRadioButtons();

        for (int i = 0; i < 4; i++) {
            RadioButton rb = radioButtons.get(qs.getOrder().get(i));
            URLImageParser p_rb = new URLImageParser(rb, getContext());
            Spanned htmlSpan_rb = Html.fromHtml(safeText(q.getAnswers().get(i)), p_rb, null);
            rb.setText(htmlSpan_rb);
        }

        for (RadioButton b: radioButtons) {
            // reset default color
            b.setBackgroundResource(0);
        }

        if (qs.hasAnswer()) {
            radioGroup.check(getRadioButtons().get(qs.getAnswer()).getId());
        } else {
            radioGroup.clearCheck();
        }
    }

    public QuestionState getQuestionState() {
        return questionState;
    }

    public void showCorrectAnswer() {
        final RadioButton correctButton = getRadioButtons().get(questionState.getCorrectAnswer());
        correctButton.setBackgroundResource(R.color.correctAnswer);
    }

    private void setQuestionText(String text) {
        URLImageParser p = new URLImageParser(questionTextView, getContext());
        if(this.listPosition > 0) {
            text = this.listPosition + ") " + text;
        }
        Spanned htmlSpan = Html.fromHtml(safeText(text), p, null);
        questionTextView.setText(htmlSpan);
    }

    private String safeText(final String source) {
        return replaceNNBSP && source != null ? source.replace('\u202f', '\u00a0') : source;
    }

    private List<RadioButton> getRadioButtons() {
        final List<RadioButton> radioButtons = new LinkedList<>();
        radioButtons.add((RadioButton) findViewById(R.id.radio0));
        radioButtons.add((RadioButton) findViewById(R.id.radio1));
        radioButtons.add((RadioButton) findViewById(R.id.radio2));
        radioButtons.add((RadioButton) findViewById(R.id.radio3));
        return radioButtons;
    }
}

@@ -97,34 +97,8 @@
 ld;%0A
-import android.os.Parcel;%0A
 impo
@@ -2102,2186 +2102,259 @@
 oid 
-onRestoreInstanceState(Parcelable state) %7B%0A        QuestionViewSavedState ss = (QuestionViewSavedState) state;%0A        super.onRestoreInstanceState(ss.getSuperState());%0A        for (int i = 0; i %3C getChildCount(); i++) %7B%0A            getChildAt(i).restoreHierarchyState(ss.childrenStates);%0A        %7D%0A    %7D%0A%0A    @Override%0A    protected Parcelable onSaveInstanceState() %7B%0A        Parcelable superState = super.onSaveInstanceState();%0A        QuestionViewSavedState ss = new QuestionViewSavedState(superState);%0A        for (int i =0; i %3C getChildCount(); i++) %7B%0A            getChildAt(i).saveHierarchyState(ss.childrenStates);%0A        %7D%0A        return ss;%0A    %7D%0A%0A    @Override%0A    protected void dispatchSaveInstanceState(SparseArray%3CParcelable%3E container) %7B%0A        dispatchFreezeSelfOnly(container);%0A    %7D%0A%0A    @Override%0A    protected void dispatchRestoreInstanceState(SparseArray%3CParcelable%3E container) %7B%0A        dispatchThawSelfOnly(container);%0A    %7D%0A%0A    private static class QuestionViewSavedState extends BaseSavedState %7B%0A        SparseArray childrenStates = new SparseArray%3C%3E();%0A%0A        QuestionViewSavedState(Parcelable superState) %7B%0A            super(superState);%0A        %7D%0A%0A        private QuestionViewSavedState(Parcel in, ClassLoader classLoader) %7B%0A            super(in);%0A            childrenStates = in.readSparseArray(classLoader);%0A        %7D%0A%0A        @Override%0A        public void writeToParcel(Parcel out, int flags) %7B%0A            super.writeToParcel(out, flags);%0A            out.writeSparseArray(childrenStates);%0A        %7D%0A%0A        public static final ClassLoaderCreator%3CQuestionViewSavedState%3E CREATOR%0A                = new ClassLoaderCreator%3CQuestionViewSavedState%3E() %7B%0A            @Override%0A            public QuestionViewSavedState createFromParcel(Parcel in, ClassLoader loader) %7B%0A                return new QuestionViewSavedState(in, loader);%0A            %7D%0A%0A            @Override%0A            public QuestionViewSavedState createFromParcel(Parcel in) %7B%0A                return createFromParcel(null);%0A            %7D%0A%0A            public QuestionViewSavedState%5B%5D newArray(int size) %7B%0A                return new QuestionViewSavedState%5Bsize%5D;%0A            %7D%0A        %7D
+dispatchSaveInstanceState(SparseArray%3CParcelable%3E container) %7B%0A        dispatchFreezeSelfOnly(container);%0A    %7D%0A%0A    @Override%0A    protected void dispatchRestoreInstanceState(SparseArray%3CParcelable%3E container) %7B%0A        dispatchThawSelfOnly(container)
 ;%0A  

remove the now obsolete state object