package com.bernard.mcqinator.view.activities;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.bernard.mcqinator.R;
import com.bernard.mcqinator.api.QuizMetadata;
import com.bernard.mcqinator.controller.FileManager;
import com.bernard.mcqinator.controller.QuizMetadataManager;
import com.bernard.mcqinator.view.QuizAdapter;
import com.bernard.mcqinator.view.TextBackgroundManager;

import java.io.File;
import java.io.IOException;

public class QuizManagerActivity extends ListActivity{

    TextBackgroundManager tbm;
    public static final String VICTIM_QUIZ_FILEID = "com.bernard.qcminator.VICTIM_QUIZ_FILEID";
    public static final int CHOOSING_FILE_TO_IMPORT = 0x55BB2B3A;
    QuizAdapter qa;

    //////////// Activity lifecycle ////////////

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz_manager);
        tbm = new TextBackgroundManager(this);

        Button importQuiz = findViewById(R.id.importQuiz);
        importQuiz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.setType("file/*");
                try{
                    startActivityForResult(Intent.createChooser(i,"Select a file to import"),CHOOSING_FILE_TO_IMPORT);
                }catch(ActivityNotFoundException e){
                    Toast.makeText(QuizManagerActivity.this, R.string.noFileReader, Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        reloadQuizz();
        tbm.stopTexts();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        tbm.restartTexts();
    }

    public void reloadQuizz(){
        qa = new QuizAdapter(QuizMetadataManager.getAll(this),this);
        setListAdapter(qa);
    }


    //////////// Listeners ////////////

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        DialogFragment fragment = new WhatToDoToQuiz();
        Bundle args = new Bundle();
        args.putLong(VICTIM_QUIZ_FILEID,qa.getItem(position).getFileID());
        fragment.setArguments(args);
        fragment.show(getFragmentManager(),"QuizWhatToDo");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CHOOSING_FILE_TO_IMPORT && resultCode == RESULT_OK){
            String path = data.getData().getPath();
            Log.d("Import file","Importing "+path);
            try {
                File f = new File(path);
                if(!f.canRead()){
                    Toast.makeText(this, R.string.unreadableFile, Toast.LENGTH_LONG).show();
                    return;
                }

                QuizMetadata meta = FileManager.importQuizFromFile(this,f);
                QuizMetadataManager.saveSavedQuizList(this);
                assert meta != null;
                Toast.makeText(this, getResources().getString(R.string.successfullyImportedQuiz, meta.getName()), Toast.LENGTH_LONG).show();
            } catch (IOException | NullPointerException | AssertionError e) {
                Log.e("ImportQuiz","Failed importing quiz",e);
                Toast.makeText(this, getResources().getString(R.string.failedImportQuiz), Toast.LENGTH_LONG).show();
            }

        }
    }

    //////////// Internal classes ////////////

    ////// Dialogs //////

    public static class WhatToDoToQuiz extends DialogFragment {

        @Override
        public Dialog onCreateDialog(final Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.whatToDoToQuiz)
                    .setItems(R.array.quizManageOption, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0://Delete
                                    DialogFragment fragment = new ReallyWantToDelete();
                                    Bundle args = new Bundle();
                                    args.putLong(VICTIM_QUIZ_FILEID, getArguments().getLong(VICTIM_QUIZ_FILEID));
                                    fragment.setArguments(args);
                                    fragment.show(getFragmentManager(), "QuizReallyWantToDelete");
                                    break;
                                case 1://Export
                                    QuizMetadata q = QuizMetadataManager.getQuiz(getActivity(),getArguments().getLong(VICTIM_QUIZ_FILEID));
                                    if(q == null){
                                        Log.e("ExportQuiz","Quiz not found");
                                        Toast.makeText(getActivity(), "Cannot export quiz ... quiz not found", Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                    String fileName;
                                    File f;
                                    int i = 0;
                                    do {
                                        fileName = q.getName() + "-" + q.getAuthor() + ((i!=0)?("("+i+")"):"") +".bernard";
                                        i++;
                                    }while((f = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),fileName)).exists());
                                    try {
                                        if(!f.createNewFile())throw new IOException("The file exists ... this error is nor supposed to be");
                                        FileManager.exportQuizToFile(q,getActivity(),f);
                                        Toast.makeText(getActivity(), getResources().getString(R.string.successfullyExportQuizTo,fileName), Toast.LENGTH_SHORT).show();
                                    } catch (IOException e) {
                                        Log.d("ExportFile","Can't export the file to "+fileName,e);
                                        Toast.makeText(getActivity(), getResources().getString(R.string.failedExportQuizTo,fileName), Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                                case 2://Duplicate
                                    DialogFragment fragment3 = new DuplicateOptions();
                                    Bundle args3 = new Bundle();
                                    args3.putLong(VICTIM_QUIZ_FILEID, getArguments().getLong(VICTIM_QUIZ_FILEID));
                                    fragment3.setArguments(args3);
                                    fragment3.show(getFragmentManager(), "QuizReallyWantToDelete");
                                    break;
                            }
                        }
                    });


            return builder.create();
        }

    }

    public static class ReallyWantToDelete extends DialogFragment {

        @Override
        public void onDismiss(DialogInterface dialog) {
            super.onDismiss(dialog);
            if(getActivity() instanceof QuizManagerActivity)
                ((QuizManagerActivity)getActivity()).reloadQuizz();
        }

        @Override
        public Dialog onCreateDialog(final Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(R.string.reallyWantToDelete)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            QuizMetadata q = QuizMetadataManager.getQuiz(getActivity(),getArguments().getLong(VICTIM_QUIZ_FILEID));
                            if (q == null) {
                                Log.e("DeleteQuiz", "The quiz reference was null, cannot delete quiz");
                                Toast.makeText(getActivity(), R.string.cannotDeleteQuiz, Toast.LENGTH_LONG).show();
                                return;
                            }
                            if (FileManager.delete(q,getActivity()))
                                Toast.makeText(getActivity(), getResources().getString(R.string.successfullyDeleteQuiz, q.getName()), Toast.LENGTH_LONG).show();
                            else
                                Toast.makeText(getActivity(), getResources().getString(R.string.failedDeleteQuiz, q.getName()), Toast.LENGTH_LONG).show();
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(getActivity(), android.R.string.ok, Toast.LENGTH_SHORT).show();
                        }
                    });


            return builder.create();
        }

    }

    public static class DuplicateOptions extends DialogFragment {

        @Override
        public void onDismiss(DialogInterface dialog) {
            super.onDismiss(dialog);
            if(getActivity() instanceof QuizManagerActivity)
                ((QuizManagerActivity)getActivity()).reloadQuizz();
        }

        @SuppressLint("InflateParams")
        @Override
        public Dialog onCreateDialog(final Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            LayoutInflater inflater = getActivity().getLayoutInflater();
            builder.setMessage(R.string.newDuplicateData)
                    .setView(inflater.inflate(R.layout.duplication_options_layout, null,false))
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Context c = getActivity();
                            QuizMetadata q = QuizMetadataManager.getQuiz(getActivity(),getArguments().getLong(VICTIM_QUIZ_FILEID));
                            if (q == null) {
                                Log.d("DuplicateQuiz", "The quiz reference was null, cannot duplicate quiz");
                                Toast.makeText(getActivity(), R.string.failedDuplicateQuiz, Toast.LENGTH_LONG).show();
                                return;
                            }
                            String newName = ((EditText)getDialog().findViewById(R.id.newNameAsk)).getText().toString();
                            String newAuthor = ((EditText)getDialog().findViewById(R.id.newAuthorAsk)).getText().toString();
                            if(newAuthor.isEmpty())
                                newAuthor = q.getAuthor();
                            try {
                                QuizMetadataManager.createQuiz(c,newName,newAuthor,true,q);
                                Toast.makeText(getActivity(), getResources().getString(R.string.successfullyDuplicateQuiz, q.getName()), Toast.LENGTH_LONG).show();
                            } catch (Exception e) {
                                Log.e("Quizduplication","Cannot duplicate quiz : ",e);
                                Toast.makeText(getActivity(), getResources().getString(R.string.failedDuplicateQuiz), Toast.LENGTH_LONG).show();
                            }
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(getActivity(), android.R.string.ok, Toast.LENGTH_SHORT).show();
                        }
                    });



            return builder.create();
        }

    }

}
