package com.bernard.mcqinator.api.frageable;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bernard.mcqinator.R;
import com.bernard.mcqinator.api.fragen.BlocFrage;
import com.bernard.mcqinator.api.fragen.Frage;
import com.bernard.mcqinator.api.fragenStats.QuizStat;
import com.bernard.mcqinator.view.activities.MainActivity;
import com.bernard.mcqinator.view.activities.fragenActivities.BlocFrageActivity;
import com.bernard.mcqinator.view.activities.fragenActivities.FrageActivity;

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

public interface BlocFrageable<S extends QuizStat,ID extends Frage.Identifier> extends Frageable<BlocFrageable.BlocData,BlocFrage.Reply,BlocFrageable.BlocConfigurator,S,ID,BlocFrage> {

    int[] useableBlocCount = {2,3,4,6,8};
    Class <? extends Frageable.Configurator> CONFIGURATOR = BlocConfigurator.class;
    String LAST_BLOC_VALUE = "com.bernard.qcminator.LAST_BLOC_VALUE";
    String LAST_FRAGE_COUNT = "com.bernard.qcminator.LAST_BLOC_FRAGE_COUNT";
    int DEFAULT_FRAGE_COUNT = 10;
    int DEFAULT_FRAGE_COUNT_MAX = 50;
    int DEFAULT_BLOC_VALUE = 2;

    class BlocData extends Frageable.Data{
        public final int blockNumber;
        public final int length;


        public BlocData(int blockNumber, int length) {
            this.blockNumber = blockNumber;
            this.length = length;
        }

        public int getBlockNumber() {
            return blockNumber;
        }

        public int getLength() {
            return length;
        }

        @Override
        public Class<? extends FrageActivity<? extends Frage>> getFrageActivityClass() {
            return BlocFrageActivity.class;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(blockNumber);
            dest.writeInt(length);
        }

        public static Parcelable.Creator<BlocData> CREATOR = new Parcelable.Creator<BlocData>(){
            @Override
            public BlocData createFromParcel(Parcel source) {
                return new BlocData(source.readInt(),source.readInt());
            }

            @Override
            public BlocData[] newArray(int size) {
                return new BlocData[size];
            }
        };
    }

    class BlocConfigurator extends Frageable.Configurator{
        public int lastBlocCountIndex = 0;

        @Override
        public View attachConfigLayout(final Activity a,ViewGroup frame) {
            final View layout = a.getLayoutInflater().inflate(R.layout.bloc_frage_options_layout,frame);
            final Button blocCountButton = layout.findViewById(R.id.blocCount);
            final TextView frageCountText = layout.findViewById(R.id.frageCountText);
            final SeekBar frageCountBar = layout.findViewById(R.id.frageCount);

            SharedPreferences preferences = a.getSharedPreferences(MainActivity.PREFERENCES_FILE_KEY,Context.MODE_PRIVATE);
            lastBlocCountIndex = preferences.getInt(LAST_BLOC_VALUE,DEFAULT_BLOC_VALUE);
            int realBlocCount = (lastBlocCountIndex>=0)?useableBlocCount[lastBlocCountIndex]:-lastBlocCountIndex;

            blocCountButton.setText(a.getResources().getString(R.string.blocPerFrage,Integer.toString(realBlocCount,10)));

            blocCountButton.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(a);
                    builder.setTitle(R.string.blocCountAsk);
                    final EditText blocCountPrompt = new EditText(a);
                    blocCountPrompt.setInputType(InputType.TYPE_CLASS_NUMBER);
                    builder.setView(blocCountPrompt);
                    builder.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int n = Integer.parseInt(blocCountPrompt.getText().toString(), 10);
                                lastBlocCountIndex = -n;
                            }catch(Exception e){
                                Log.e("BlocCountDialog","Cannot read data",e);
                                Toast.makeText(a, R.string.failedSettingBlocCountValue, Toast.LENGTH_SHORT).show();
                            }
                            int realBlocCount = (lastBlocCountIndex>=0)?useableBlocCount[lastBlocCountIndex]:-lastBlocCountIndex;
                            blocCountButton.setText(a.getResources().getString(R.string.blocPerFrage,Integer.toString(realBlocCount,10)));

                            if(realBlocCount > 10){
                                AlertDialog.Builder builder = new AlertDialog.Builder(a);
                                builder.setTitle(R.string.achtung);
                                builder.setIcon(android.R.drawable.ic_dialog_alert);
                                builder.setPositiveButton(android.R.string.ok,null);
                                TextView texte = new TextView(a);
                                texte.setText(R.string.blocCountABitHigh);
                                builder.setView(texte);
                                builder.show();
                            }
                        }
                    });
                    builder.setNegativeButton(android.R.string.no,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();


                    return true;
                }
            });
            blocCountButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.v("BCButton","simple click !");
                    lastBlocCountIndex = (lastBlocCountIndex < 0)?DEFAULT_BLOC_VALUE:(lastBlocCountIndex + 1 >= useableBlocCount.length)?0:lastBlocCountIndex+1;
                    int realBlocCount = (lastBlocCountIndex>=0)?useableBlocCount[lastBlocCountIndex]:-lastBlocCountIndex;

                    blocCountButton.setText(a.getResources().getString(R.string.blocPerFrage,Integer.toString(realBlocCount,10)));
                }
            });

            frageCountBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    frageCountText.setText(a.getResources().getString(R.string.fragCount,progress));
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            View.OnLongClickListener frageCountLongListener = new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Log.v("frageCount","looooooooooooong");
                    AlertDialog.Builder builder = new AlertDialog.Builder(a);
                    builder.setTitle(R.string.frageCountAsk);
                    final EditText frageCountPrompt = new EditText(a);
                    frageCountPrompt.setInputType(InputType.TYPE_CLASS_NUMBER);
                    builder.setView(frageCountPrompt);
                    builder.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int n = Integer.parseInt(frageCountPrompt.getText().toString(), 10);
                                if(n>DEFAULT_FRAGE_COUNT_MAX)
                                    frageCountBar.setMax(n);
                                else
                                    frageCountBar.setMax(DEFAULT_FRAGE_COUNT_MAX);
                                frageCountBar.setProgress(n);
                            }catch(Exception e){
                                Log.e("FrageCountDialog","Cannot read data",e);
                                Toast.makeText(a, R.string.failedSettingFrageCountValue, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    builder.setNegativeButton(android.R.string.no,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();


                    return false;
                }
            };
            frageCountText.setLongClickable(true);
            frageCountBar.setLongClickable(true);

            frageCountBar.setOnLongClickListener(frageCountLongListener);
            frageCountText.setOnLongClickListener(frageCountLongListener);

            frageCountBar.setProgress(preferences.getInt(LAST_FRAGE_COUNT,DEFAULT_FRAGE_COUNT));

            return layout;
        }

        @Override
        public int getTypStringID() {
            return R.string.blocQuiz;
        }

        @Override
        public int getIconDrawableID() {
            return R.drawable.bloc_quiz_icon;
        }

        @Override
        public Data genDataFromConfigLayout(View v) {
            SeekBar fC = v.findViewById(R.id.frageCount);
            int realBlocCount = (lastBlocCountIndex>=0)?useableBlocCount[lastBlocCountIndex]:-lastBlocCountIndex;
            BlocData bdata =  new BlocData(realBlocCount,fC.getProgress());
            Log.v("BlocData","Selected : "+bdata.blockNumber+","+bdata.length);
            return bdata;
        }
    }

}
