package com.ericsson.uecontrol.gui.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;

import com.ericsson.uecontrol.R;
import com.ericsson.uecontrol.core.UeBehaviour;

import org.apache.log4j.Logger;

public class SelectBehaviourDialog extends DialogFragment {
    private static final Logger log = Logger.getLogger(SelectBehaviourDialog.class);
    public static String[] behaviourClasses;
    public static String[] behaviourNames;

    private BehaviourSelectionCallback callback;


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Generate nice behaviour names
        if(behaviourClasses == null) {
            behaviourClasses = getResources().getStringArray(R.array.behaviours);
            behaviourNames = new String[behaviourClasses.length];

            for (int i = 0; i < behaviourClasses.length; i++) {
                try {
                    UeBehaviour obj = (UeBehaviour) Class.forName(behaviourClasses[i]).newInstance();
                    behaviourNames[i] = obj.getName();
                }catch(Exception e){
                    log.warn(null, e);
                    behaviourNames[i] = behaviourClasses[i];
                }
            }
        }

        // Create dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.select_behaviour);
        builder.setItems(behaviourNames, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (callback != null){
                                Class objClass = Class.forName(behaviourClasses[which]);
                                callback.behaviourSelected(behaviourNames[which], objClass);
                            }
                        } catch (Exception e) {
                            log.warn(null, e);
                        }
                    }
                });
        return builder.create();
    }

    public void setSelectionCallback(BehaviourSelectionCallback c){
        callback = c;
    }

    public static interface BehaviourSelectionCallback{
        public void behaviourSelected(String name, Class<UeBehaviour> objClass);
    }
}