package com.example.tyre.util;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.tyre.R;

import java.util.List;

public class CarSelectionDialog extends Dialog {
    private ListView carListView;
    private CarListAdapter adapter;
    private OnCarSelectedListener listener;
    private List<String> carNoList;

    public CarSelectionDialog(Context context, List<String> carNoList) {
        super(context);
        this.carNoList = carNoList;
        initDialog();
    }

    private void initDialog() {
        setContentView(R.layout.dialog_car_selection);
        setCanceledOnTouchOutside(true);

        carListView = findViewById(R.id.car_list_view);
        adapter = new CarListAdapter(getContext(), carNoList);
        carListView.setAdapter(adapter);

        carListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (listener != null) {
                    listener.onCarSelected(carNoList.get(position));
                }
                dismiss();
            }
        });

        findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    public void setOnCarSelectedListener(OnCarSelectedListener listener) {
        this.listener = listener;
    }

    public interface OnCarSelectedListener {
        void onCarSelected(String carNo);
    }

    private static class CarListAdapter extends BaseAdapter {
        private Context context;
        private List<String> carList;

        public CarListAdapter(Context context, List<String> carList) {
            this.context = context;
            this.carList = carList;
        }

        @Override
        public int getCount() {
            return carList.size();
        }

        @Override
        public Object getItem(int position) {
            return carList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
            }
            TextView textView = convertView.findViewById(android.R.id.text1);
            textView.setText(carList.get(position));
            return convertView;
        }
    }
}
