package com.tsi.navi.activity.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.tsi.navi.R;
import com.tsi.navi.TsiNaviApplication;
import com.tsi.navi.activity.model.SignalItem;
import com.tsi.navi.dto.enums.eLightsStatus;
import com.tsi.navi.dto.enums.eLightsType;
import com.tsi.navi.util.TsiUtils;

import java.util.ArrayList;

public class UserSignalItemAdapter extends RecyclerView.Adapter<UserSignalItemAdapter.ViewHolder> implements Filterable {

    private static final String TAG = UserSignalItemAdapter.class.getSimpleName();

    private int[] drawId = {
            R.drawable.rect_off,            // LIGHTS_OUT   (0, "LIGHTS_OUT"),     //소등
            R.drawable.rect_red,            // RED_SOLID    (1, "RED_SOLID"),      //적색점등
            R.drawable.rect_yellow,         // YELLOW_SOLID (2, "YELLOW_SOLID"),   //황색점등
            R.drawable.rect_green,          // GREEN_SOLID  (3, "GREEN_SOLID"),    //녹색점등
            R.drawable.rect_red_blink,      // RED_BLINK    (4, "RED_BLINK"),      //적색점멸
            R.drawable.rect_yellow_blink,   // YELLOW_BLINK (5, "YELLOW_BLINK"),   //황색점멸
            R.drawable.rect_green_blink,    // GREEN_BLINK  (6, "GREEN_BLINK");    //녹색점멸
            R.drawable.rect_none,           // 데이터 없음.
    };
    private int[] drawIdUn = {
            R.drawable.rect_off,            // LIGHTS_OUT   (0, "LIGHTS_OUT"),     //소등
            R.drawable.rect_red_un,            // RED_SOLID    (1, "RED_SOLID"),      //적색점등
            R.drawable.rect_yellow_un,         // YELLOW_SOLID (2, "YELLOW_SOLID"),   //황색점등
            R.drawable.rect_green_un,          // GREEN_SOLID  (3, "GREEN_SOLID"),    //녹색점등
            R.drawable.rect_red_blink,      // RED_BLINK    (4, "RED_BLINK"),      //적색점멸
            R.drawable.rect_yellow_blink,   // YELLOW_BLINK (5, "YELLOW_BLINK"),   //황색점멸
            R.drawable.rect_green_blink,    // GREEN_BLINK  (6, "GREEN_BLINK");    //녹색점멸
            R.drawable.rect_none,           // 데이터 없음.
    };
    private int[] textColor = {
            Color.WHITE,            // LIGHTS_OUT   (0, "LIGHTS_OUT"),     //소등
            Color.WHITE,           // RED_SOLID    (1, "RED_SOLID"),      //적색점등
            Color.BLACK,         // YELLOW_SOLID (2, "YELLOW_SOLID"),   //황색점등
            Color.WHITE,          // GREEN_SOLID  (3, "GREEN_SOLID"),    //녹색점등
            Color.WHITE,      // RED_BLINK    (4, "RED_BLINK"),      //적색점멸
            Color.BLACK,   // YELLOW_BLINK (5, "YELLOW_BLINK"),   //황색점멸
            Color.BLACK,    // GREEN_BLINK  (6, "GREEN_BLINK");    //녹색점멸
            Color.WHITE,           // 데이터 없음.
    };

    // FOR interface - start
    public interface OnItemClickListener {
        void onItemClick(View v, int pos, SignalItem item);
    }
    private OnItemClickListener onItemClickListener = null;
    public void setOnItemClickListener(OnItemClickListener listener) {
        onItemClickListener = listener;
    }
    // FOR interface - end.

    private Context context;
    private ArrayList<SignalItem> unFilteredList = new ArrayList<>();
    private ArrayList<SignalItem> filteredList = new ArrayList<>();
    private int normalTextColor;
    private int activeTextColor;


    public UserSignalItemAdapter(Context context, ArrayList<SignalItem> list) {
        super();
        this.context = context;
        this.unFilteredList = list;
        this.filteredList = list;
        this.normalTextColor = ContextCompat.getColor(this.context, R.color.rect_normal_color);
        this.activeTextColor = ContextCompat.getColor(this.context, R.color.rect_active_color);
    }

    @NonNull
    @Override
    public UserSignalItemAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user_signal, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull UserSignalItemAdapter.ViewHolder holder, int position) {
        holder.onBind(filteredList.get(position));
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setItems(ArrayList<SignalItem> list){
        this.unFilteredList = list;
        this.filteredList = list;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        if (this.filteredList == null) return 0;
        return this.filteredList.size();
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                String findString = constraint.toString();
                if (findString.isEmpty()) {
                    filteredList = unFilteredList;
                }
                else {
                    ArrayList<SignalItem> filteringList = new ArrayList<>();
                    Log.e(TAG, "SignalItem: " + unFilteredList.size() + " EA. ==> " + findString);
                    for (SignalItem obj : unFilteredList) {
                        if (String.valueOf(obj.getDirection()).contains(findString)) {
                            Log.e(TAG, "match id: " + obj.getDirection());
                            filteringList.add(obj);
                        }
                    }
                    filteredList = filteringList;
                }
                FilterResults filterResults = new FilterResults();
                filterResults.values = filteredList;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                filteredList = (ArrayList<SignalItem>)results.values;
                notifyDataSetChanged();
            }
        };
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView[] tvSignal = new TextView[TsiUtils.MAX_LIGHT_TYPE];

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            this.tvSignal[0]                                 = (TextView) itemView.findViewById(R.id.tv_direction);
            this.tvSignal[eLightsType.STRAIGHT.getValue()]   = (TextView) itemView.findViewById(R.id.tv_straight);
            this.tvSignal[eLightsType.LEFT_TURN.getValue()]  = (TextView) itemView.findViewById(R.id.tv_left_turn);
            this.tvSignal[eLightsType.PEDESTRIAN.getValue()] = (TextView) itemView.findViewById(R.id.tv_walker);
            this.tvSignal[eLightsType.BICYCLE.getValue()]    = (TextView) itemView.findViewById(R.id.tv_bicycle);
            this.tvSignal[eLightsType.RIGHT_TURN.getValue()] = (TextView) itemView.findViewById(R.id.tv_right_turn);
            this.tvSignal[eLightsType.BUS.getValue()]        = (TextView) itemView.findViewById(R.id.tv_bus);
            this.tvSignal[eLightsType.U_TURN.getValue()]     = (TextView) itemView.findViewById(R.id.tv_u_turn);
        }

        @SuppressLint("SetTextI18n")
        void onBind(SignalItem item) {
            if (item == null) return;

            this.tvSignal[0].setText(TsiNaviApplication.getDirection().getName(item.getDirection()));
/*
            if      (item.getDirection() == 10) this.tvSignal[0].setText("북(10)");
            else if (item.getDirection() == 20) this.tvSignal[0].setText("동(20)");
            else if (item.getDirection() == 30) this.tvSignal[0].setText("남(30)");
            else if (item.getDirection() == 40) this.tvSignal[0].setText("서(40)");
            else if (item.getDirection() == 50) this.tvSignal[0].setText("북동(50)");
            else if (item.getDirection() == 60) this.tvSignal[0].setText("남동(60)");
            else if (item.getDirection() == 70) this.tvSignal[0].setText("남서(70)");
            else if (item.getDirection() == 80) this.tvSignal[0].setText("북서(80)");
            else                                this.tvSignal[0].setText("(" + item.getDirection() + ")");
*/

            int lightStatus;
            int remainSeconds;
            boolean unProtected;
            for (int ii = TsiUtils.SIGNAL_STRAIGHT; ii <= TsiUtils.SIGNAL_U_TURN; ii++) {
                lightStatus = item.getLightStatus(ii);
                remainSeconds = item.getRemainTime(ii);
                unProtected = item.getUnprotect(ii);

                if (lightStatus >= eLightsStatus.LIGHTS_OUT.getValue() && lightStatus <= eLightsStatus.GREEN_BLINK.getValue()) {
                    this.tvSignal[ii].setBackgroundResource(unProtected ? drawIdUn[lightStatus] : drawId[lightStatus]);
                    this.tvSignal[ii].setText(String.valueOf(remainSeconds));
                    this.tvSignal[ii].setTextColor(textColor[lightStatus]);
                }
                else {
                    this.tvSignal[ii].setBackgroundResource(R.drawable.rect_none);
                    this.tvSignal[ii].setText("");
                }
            }
        }
    }
}
