package com.bernard.mcqinator.view.quizEditing.formQuiz;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bernard.mcqinator.R;
import com.bernard.mcqinator.api.quiz.FormQuiz;
import com.bernard.mcqinator.controller.FileManager;
import com.bernard.mcqinator.controller.QuizMetadataManager;
import com.bernard.mcqinator.inutil.ArrayInutil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class EditFormQuizItem extends Activity implements View.OnClickListener{

    public static final String EDITED_ITEM = "com.bernard.qcminator.EDITED_ITEM";
    public static final String QUIZ_FILEID = "com.bernard.qcminator.QUIZ_FILEID";
    public static final String TO_EDIT_ITEM = "com.bernard.qcminator.TO_EDIT_ITEM";
    public static final String ITEM_POSITION = "com.bernard.qcminator.ITEM_POSITION";

    View[] addButtons;
    ViewGroup[] formsLayout;
    ViewGroup itemLayout;
    List<View> falseFields;
    FormQuiz quiz;

    final View.OnClickListener delFalshItemOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO ask confirmation if editText not empty
            //TODO check cast
            int pos = (int)v.getTag(R.id.itemLayout);
            ((ViewGroup)falseFields.get(pos).getParent()).removeView(falseFields.get(pos));
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            quiz = (FormQuiz) FileManager.getQuiz(QuizMetadataManager.getQuiz(this,getIntent().getLongExtra(QUIZ_FILEID,0)),this);
            if(quiz == null)throw new IOException("FileManager.getQuiz returned null ...");
        } catch (IOException e) {
            e.printStackTrace();//TODO customize error log
            return;
        }

        setContentView(quiz.getEditItemActivityLayoutID());

        final FormQuiz.Item item = (getIntent().getParcelableExtra(TO_EDIT_ITEM)!=null)?(FormQuiz.Item)getIntent().getParcelableExtra(TO_EDIT_ITEM):new FormQuiz.Item(new FormQuiz.Item.Form[quiz.getFormCount()]);

        formsLayout = new LinearLayout[item.getForms().length];
        addButtons = new View[item.getForms().length];
        falseFields = new ArrayList<>();

        itemLayout = findViewById(R.id.itemLayout);
        //TODO add exception if ids missing
        for (int i = 0; i < item.getForms().length; i++) {
            formsLayout[i] = (ViewGroup)getLayoutInflater().inflate(quiz.getEditItemActivityFormLayoutID(),itemLayout,false);
            TextView richtig = formsLayout[i].findViewById(R.id.realItem);
            richtig.setText(item.getForms()[i].getRichtig());

            TextView formName = formsLayout[i].findViewById(R.id.formName);
            formName.setText(quiz.getFormNameStringId(i));

            View addItemButton = formsLayout[i].findViewById(R.id.addButton);
            addItemButton.setOnClickListener(this);
            addButtons[i] = addItemButton;
            itemLayout.addView(formsLayout[i]);

            for (int j = 0; j < item.getForms()[i].getFalshe().length; j++) {
                View falshe = getLayoutInflater().inflate(R.layout.edit_form_quiz_item_false,formsLayout[i],false);
                TextView falseField = falshe.findViewById(R.id.falshItem);
                falseField.setTag(R.id.falshItem,i);
                falseField.setText(item.getForms()[i].getFalshe()[j]);
                View delFalseButton = falshe.findViewById(R.id.delFalshItemButton);
                delFalseButton.setTag(R.id.itemLayout,falseFields.size());
                delFalseButton.setOnClickListener(delFalshItemOnClickListener);
                formsLayout[i].addView(falshe);
            }
        }

        Button doneButton = findViewById(R.id.doneButton);//TODO check exists
        doneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Resources r = EditFormQuizItem.this.getResources();
                FormQuiz.Item.Form[] forms = new FormQuiz.Item.Form[formsLayout.length];
                for (int i = 0; i < item.getForms().length; i++) {
                    ArrayList<String> falshe = new ArrayList<>();
                    String realItem = ((TextView)formsLayout[i].findViewById(R.id.realItem)).getText().toString();
                    if(realItem.isEmpty()){
                        String e = r.getString(R.string.missingReal,r.getString(quiz.getFormNameStringId(i)));
                        Log.i("ParsingResults", e);
                        Toast.makeText(EditFormQuizItem.this,e,Toast.LENGTH_SHORT).show();
                        return;
                    }
                    List<View> childs = getAllChildren(formsLayout[i]);
                    for (View child : childs) {
                        if(child.getTag(R.id.falshItem) == null)
                            continue;
                        String s = ((TextView)child).getText().toString();
                        if(!s.isEmpty()) falshe.add(s);
                    }
                    Log.v("Configurator","FalsheAntwort : " + falshe);
                    String[] falsharray = new String[falshe.size()];
                    falshe.toArray(falsharray);
                    forms[i] = new FormQuiz.Item.Form((byte)0/* TODO implement formID */,realItem,falsharray);
                }

                FormQuiz.Item newItem = new FormQuiz.Item(forms);
                Intent i = new Intent();

                i.putExtra(EDITED_ITEM,(Parcelable)newItem);

                setResult(RESULT_OK,i);
                finish();
            }
        });
    }

    public static List<View> getAllChildren(View v){
        return getAllChildren(v,new ArrayList<View>());
    }

    private static List<View> getAllChildren(View v,List<View> l){
        l.add(v);
        if(v instanceof ViewGroup){
            ViewGroup vg = (ViewGroup)v;
            for (int i = 0; i < vg.getChildCount(); i++)
                getAllChildren(vg.getChildAt(i),l);
        }
        return l;
    }

    @Override
    public void onClick(View v) {
        int buttonPos = ArrayInutil.indexOf(addButtons,v);

        View falshe = getLayoutInflater().inflate(R.layout.edit_form_quiz_item_false,formsLayout[buttonPos],false);
        TextView falseField = falshe.findViewById(R.id.falshItem);
        View delFalseButton = falshe.findViewById(R.id.delFalshItemButton);
        falseField.setTag(R.id.falshItem,buttonPos);
        delFalseButton.setTag(R.id.itemLayout,falseFields.size());
        delFalseButton.setOnClickListener(delFalshItemOnClickListener);
        falseFields.add(falshe);
        formsLayout[buttonPos].addView(falshe);
    }
}
