package kz.com.aman.kassa.bank.gui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import kz.com.aman.kassa.R;


public class SelectElementDialog<ElementType> extends Dialog {
    private Context context;
    ArrayAdapter<ElementType> listAdapter;
    private TextView labelTitle;
    private ListView list;
    private SelectDialogCallback<ElementType> selectDialogCallback;

    public SelectElementDialog(final Context context, List<ElementType> elements, SelectDialogCallback<ElementType> selectDialogCallback) {
        super(context);
        this.context = context;
        this.selectDialogCallback = selectDialogCallback;
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        init(elements);
        list.setAdapter(listAdapter);
        getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        list.setOnItemClickListener((arg0, arg1, arg2, arg3) -> {
            ElementType element = (ElementType) arg0.getItemAtPosition(arg2);
            selectDialogCallback.onElementSelected(element);
            ((Activity) context).runOnUiThread(this::dismiss);
        });
    }

    private void init(List<ElementType> elements) {
        setContentView(R.layout.custom_dialog_list);
        labelTitle = findViewById(R.id.labelMessage);
        list = findViewById(R.id.list);
        listAdapter = new ArrayAdapter<ElementType>(context, R.layout.list_item, R.id.itemView, elements);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public void setTitle(String text) {
        if (null != labelTitle)
            labelTitle.setText(text);
    }

    public static void showError(Context context, String message) {
        try {
            Dialog dialog = new Dialog(context);
            dialog.setTitle(message);
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}