package kr.co.compcarecompany.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.ArraySet;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import kr.co.compcarecompany.Data.Product.RelayData;
import kr.co.compcarecompany.R;

public class ModifyScheduleDialog extends Dialog {

    Context context;
    private Handler hdr;
    private Spinner start_daySN, end_daySN;
    private TextView add_scheduleTV, start_divideTV, end_divideTV, schedule_dlg_titleTV;
    private EditText schedule_memoET;
    private ArraySet<String> start_day_set, end_day_set;
    private ArrayAdapter<CharSequence> start_day_adapter;
    private ArrayAdapter<CharSequence> end_day_adapter;
    private NumberPicker start_timeNP, start_minNP, end_timeNP, end_minNP;
    private int start_position, end_position;
    private ArrayList<RelayData> relay_array = new ArrayList<>();
    private RelayData relayData, oriData;
    private int mon, tue, wen, thu, fri, sat, sun, position;

    private ModifyScheduleDialog.clickListener clickListener;

    public interface clickListener {
        void clickBtn(HashMap<String, ArrayList<RelayData>> data, HashMap<String, RelayData> data2);
    }

    public ModifyScheduleDialog(@NonNull Context context, Handler hdr, ArrayList<RelayData> relay_array, RelayData relayData, int position, ModifyScheduleDialog.clickListener clickListener) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.clickListener = clickListener;
        this.relay_array = relay_array;
        this.relayData = relayData;
        this.position = position;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.dlg_add_schedule);

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        Window thisWindow = this.getWindow();

        int x = (int) (size.x * 0.95f);
        int y = (int) (size.y * 0.90f);

        thisWindow.setLayout(x, y);

        add_scheduleTV = findViewById(R.id.add_scheduleTV);
        schedule_memoET = findViewById(R.id.schedule_memoET);
        end_minNP = findViewById(R.id.end_minNP);
        end_timeNP = findViewById(R.id.end_timeNP);
        end_daySN = findViewById(R.id.end_daySN);
        start_minNP = findViewById(R.id.start_minNP);
        start_timeNP = findViewById(R.id.start_timeNP);
        start_daySN = findViewById(R.id.start_daySN);
        start_divideTV = findViewById(R.id.start_divideTV);
        end_divideTV = findViewById(R.id.end_divideTV);
        schedule_dlg_titleTV = findViewById(R.id.schedule_dlg_titleTV);

        start_day_set = new ArraySet<>();
        end_day_set = new ArraySet<>();

        if(relay_array.get(position).getRsIdx() != null) oriData = relay_array.get(position);
        relay_array.remove(position);

        //시작요일 스피너 초기화
        start_day_adapter = ArrayAdapter.createFromResource(getContext(), R.array.week, R.layout.custom_spinner_item_blue);
        start_day_adapter.setDropDownViewResource(R.layout.custom_spinner_item_blue);
        start_daySN.setAdapter(start_day_adapter);

        //종료요일 스피너 초기화
        end_day_adapter = ArrayAdapter.createFromResource(getContext(), R.array.week, R.layout.custom_spinner_item_blue);
        end_day_adapter.setDropDownViewResource(R.layout.custom_spinner_item_blue);
        end_daySN.setAdapter(end_day_adapter);

        List<String> timeValues = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            timeValues.add(String.format("%02d", i));
        }
        start_timeNP.setDisplayedValues(timeValues
                .toArray(new String[timeValues.size()]));
        start_timeNP.setMinValue(0);
        start_timeNP.setMaxValue(23);
        start_timeNP.setWrapSelectorWheel(false);
        start_timeNP.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        List<String> minValues = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            minValues.add(String.format("%02d", i));
        }
        start_minNP.setDisplayedValues(minValues
                .toArray(new String[minValues.size()]));

        start_minNP.setMinValue(0);
        start_minNP.setMaxValue(59);
        start_minNP.setWrapSelectorWheel(false);
        start_minNP.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        end_timeNP.setDisplayedValues(timeValues
                .toArray(new String[timeValues.size()]));
        end_timeNP.setMinValue(0);
        end_timeNP.setMaxValue(23);
        end_timeNP.setWrapSelectorWheel(false);
        end_timeNP.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        end_minNP.setMinValue(0);
        end_minNP.setMaxValue(59);
        end_minNP.setDisplayedValues(minValues
                .toArray(new String[minValues.size()]));
        end_minNP.setWrapSelectorWheel(false);
        end_minNP.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        if (relay_array.size() > 0) {
            for (int i = 0; i < relay_array.size(); i++) {
                switch (relay_array.get(i).getRsStartDay()) {
                    case "0":
                        sun++;
                        break;
                    case "1":
                        mon++;
                        break;
                    case "2":
                        tue++;
                        break;
                    case "3":
                        wen++;
                        break;
                    case "4":
                        thu++;
                        break;
                    case "5":
                        fri++;
                        break;
                    case "6":
                        sat++;
                        break;
                }
            }
        }

        set_Contents();
        init_Listener();
    }

    void set_Contents() {

        int start_day = Integer.parseInt(relayData.getRsStartDay());
        int end_day = Integer.parseInt(relayData.getRsEndDay());
        int start_time = Integer.parseInt(relayData.getRsStartTime().substring(0, 2));
        int start_min = Integer.parseInt(relayData.getRsStartTime().substring(3, 5));
        int end_time = Integer.parseInt(relayData.getRsEndTime().substring(0, 2));
        int end_min = Integer.parseInt(relayData.getRsEndTime().substring(3, 5));

        add_scheduleTV.setText("수정");
        schedule_dlg_titleTV.setText("스케줄 수정");

        start_daySN.setSelection(start_day);
        end_daySN.setSelection(end_day);
        start_position = start_day;
        end_position = end_day;

        if (start_time > 11) {
            start_divideTV.setText("오후");
        } else {
            start_divideTV.setText("오전");
        }

        if (end_time > 11) {
            end_divideTV.setText("오후");
        } else {
            end_divideTV.setText("오전");
        }

        start_timeNP.setValue(start_time);
        start_minNP.setValue(start_min);
        end_timeNP.setValue(end_time);
        end_minNP.setValue(end_min);
    }

    void init_Listener() {

        //선택한 Air_Line
        start_daySN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        if (sun > 4) {
                            Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                            start_daySN.setSelection(start_position);
                            break;
                        }
                        end_daySN.setSelection(0);
                        start_position = 0;
                        break;
                    case 1:
                        if (mon > 4) {
                            Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                            start_daySN.setSelection(start_position);
                            break;
                        }
                        end_daySN.setSelection(1);
                        start_position = 1;
                        break;
                    case 2:
                        if (tue > 4) {
                            Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                            start_daySN.setSelection(start_position);
                            break;
                        }
                        end_daySN.setSelection(2);
                        start_position = 2;
                        break;
                    case 3:
                        if (wen > 4) {
                            Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                            start_daySN.setSelection(start_position);
                            break;
                        }
                        end_daySN.setSelection(3);
                        start_position = 3;
                        break;
                    case 4:
                        if (thu > 4) {
                            Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                            start_daySN.setSelection(start_position);
                            break;
                        }
                        end_daySN.setSelection(4);
                        start_position = 4;
                        break;
                    case 5:
                        if (fri > 4) {
                            Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                            start_daySN.setSelection(start_position);
                            break;
                        }
                        end_daySN.setSelection(5);
                        start_position = 5;
                        break;
                    case 6:
                        if (sat > 4) {
                            Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                            start_daySN.setSelection(start_position);
                            break;
                        }
                        end_daySN.setSelection(6);
                        start_position = 6;
                        break;

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        start_timeNP.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                if (newVal > 11) {
                    start_divideTV.setText("오후");
                } else {
                    start_divideTV.setText("오전");
                }
            }
        });

        end_timeNP.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                if (newVal > 11) {
                    end_divideTV.setText("오후");
                } else {
                    end_divideTV.setText("오전");
                }
            }
        });

        end_daySN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                end_position = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        add_scheduleTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int start_time = start_timeNP.getValue();
                int start_min = start_minNP.getValue();
                int end_time = end_timeNP.getValue();
                int end_min = end_minNP.getValue();
                String con_start_time = start_time + "";
                String con_start_min = start_min + "";
                String con_end_time = end_time + "";
                String con_end_min = end_min + "";

                if (start_time < 10) {
                    con_start_time = "0" + con_start_time;
                }

                if (start_min < 10) {
                    con_start_min = "0" + con_start_min;
                }

                if (end_time < 10) {
                    con_end_time = "0" + con_end_time;
                }

                if (end_min < 10) {
                    con_end_min = "0" + con_end_min;
                }

                if (start_position == end_position && start_time == end_time && start_min == end_min) {
                    Toast.makeText(getContext(), "기계를 동작할 구간을 설정해주세요.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (start_position == end_position && start_time > end_time) {
                    Toast.makeText(getContext(), "끝나는 시간이 시작 시간보다 이전일 수 없습니다.", Toast.LENGTH_SHORT).show();
                    return;

                } else if (start_position == end_position && start_time == end_time && start_min > end_min) {
                    Toast.makeText(getContext(), "끝나는 시간이 시작 시간보다 이전일 수 없습니다.", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (check_section(start_position, end_position, con_start_time, con_start_min, con_end_time, con_end_min)) {
                    Toast.makeText(getContext(), "기존에 저장한 스케줄과 겹치는 구간이 있습니다.", Toast.LENGTH_SHORT).show();
                    return;
                }

                HashMap<String, ArrayList<RelayData>> data = new HashMap<>();
//                data.put("rs_start_day", start_position + "");
//                data.put("rs_end_day", end_position + "");
//                data.put("rs_start_hour", con_start_time);
//                data.put("rs_start_min", con_start_min);
//                data.put("rs_end_hour", con_end_time);
//                data.put("rs_end_min", con_end_min);
//                data.put("rs_memo", schedule_memoET.getText().toString());

                RelayData relayData = new RelayData();
                relayData.setRsStartDay(start_position+"");
                relayData.setRsEndDay(end_position+"");
                relayData.setRsStartTime(con_start_time + ":" + con_start_min);
                relayData.setRsEndTime(con_end_time + ":" + con_end_min);
                relayData.setRsMemo(schedule_memoET.getText().toString());

                relay_array.add(relayData);
                Collections.sort(relay_array, cmpAsc);
                data.put("relay", relay_array);

                HashMap<String, RelayData> data2 = new HashMap<>();
                data2.put("modify_data", oriData);

                clickListener.clickBtn(data, data2);
                dismiss();
            }
        });
    }

    private static Comparator<RelayData> cmpAsc = new Comparator<RelayData>() {
        @Override
        public int compare(RelayData o1, RelayData o2) {
            if (o1.getRsStartDay().equals(o2.getRsStartDay())) {
                return o1.getRsStartTime().compareTo(o2.getRsStartTime());
            } else {
                return o1.getRsStartDay().compareTo(o2.getRsStartDay());
            }
        }
    };

    boolean check_section(int s_day, int e_day, String s_time, String s_min, String e_time, String e_min) {

        int new_s_time = (24 * s_day + Integer.parseInt(s_time)) * 60 + Integer.parseInt(s_min);
        int new_e_time = (24 * e_day + Integer.parseInt(e_time)) * 60 + Integer.parseInt(e_min);

        for (int i = 0; i < relay_array.size(); i++) {
            int start_day = Integer.parseInt(relay_array.get(i).getRsStartDay());
            int end_day = Integer.parseInt(relay_array.get(i).getRsEndDay());
            int start_time = Integer.parseInt(relay_array.get(i).getRsStartTime().substring(0, 2));
            int start_min = Integer.parseInt(relay_array.get(i).getRsStartTime().substring(3, 5));
            int end_time = Integer.parseInt(relay_array.get(i).getRsEndTime().substring(0, 2));
            int end_min = Integer.parseInt(relay_array.get(i).getRsEndTime().substring(3, 5));

            int start = (24 * start_day + start_time) * 60 + start_min;
            int end = (24 * end_day + end_time) * 60 + end_min;

            if (start <= new_s_time && new_s_time <= end) {
                return true;

            } else if (start <= new_e_time && new_e_time <= end) {
                return true;

            } else if (start <= new_s_time && new_e_time <= end) {
                return true;
            }
        }
        return false;
    }
}
