package kr.co.compcarecompany.Util.CustomView;

import android.app.Dialog;
import android.app.TimePickerDialog;
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.text.format.DateFormat;
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.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.HashMap;

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

public class AddScheduleDialog2 extends Dialog {

    Context context;
    private Handler hdr;
    private Spinner start_daySN, end_daySN;
    private LinearLayout startLL, endLL;
    private TextView add_scheduleTV, start_divideTV, end_divideTV, start_timeTV, start_minTV, end_timeTV, end_minTV;
    private EditText schedule_memoET;
    private ArrayAdapter<CharSequence> start_day_adapter;
    private ArrayAdapter<CharSequence> end_day_adapter;
    private int start_position, end_position;
    private ArrayList<RelayData> relay_array = new ArrayList<>();
    private int mon, tue, wen, thu, fri, sat, sun;

    private AddScheduleDialog2.clickListener clickListener;

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

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

    @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_schedule2);

        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_daySN = findViewById(R.id.end_daySN);
        start_daySN = findViewById(R.id.start_daySN);
        start_divideTV = findViewById(R.id.start_divideTV);
        end_divideTV = findViewById(R.id.end_divideTV);
        startLL = findViewById(R.id.startLL);
        start_timeTV = findViewById(R.id.start_timeTV);
        start_minTV = findViewById(R.id.start_minTV);
        endLL = findViewById(R.id.endLL);
        end_timeTV = findViewById(R.id.end_timeTV);
        end_minTV = findViewById(R.id.end_minTV);

        //시작요일 스피너 초기화
        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);

        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;
                }
            }
        }

        if (sun < 5) {
            start_daySN.setSelection(0);
        } else if (mon < 5) {
            start_daySN.setSelection(1);
        } else if (tue < 5) {
            start_daySN.setSelection(2);
        } else if (wen < 5) {
            start_daySN.setSelection(3);
        } else if (thu < 5) {
            start_daySN.setSelection(4);
        } else if (fri < 5) {
            start_daySN.setSelection(5);
        } else if (sat < 5) {
            start_daySN.setSelection(6);
        }

        init_Listener();
    }

    void init_Listener() {

        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) {
            }
        });

        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) {

            }
        });

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

                TimePickerDialog.OnTimeSetListener mTimeSetListener =
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                                if (hourOfDay < 10) {
                                    start_timeTV.setText("0" + hourOfDay);
                                    end_timeTV.setText("0" + hourOfDay);
                                } else {
                                    start_timeTV.setText(hourOfDay + "");
                                    end_timeTV.setText(hourOfDay + "");
                                }

                                if (minute < 10) {
                                    start_minTV.setText("0" + minute);
                                    end_minTV.setText("0" + minute);
                                } else {
                                    start_minTV.setText(minute + "");
                                    end_minTV.setText(minute + "");
                                }
                            }
                        };
                TimePickerDialog alert = new TimePickerDialog(getContext(), mTimeSetListener, 0, 0, DateFormat.is24HourFormat(getContext()));
                alert.setTitle("시작시간 설정");
                alert.show();
            }
        });

        endLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog.OnTimeSetListener mTimeSetListener =
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                if (hourOfDay < 10) {
                                    end_timeTV.setText("0" + hourOfDay);
                                } else {
                                    end_timeTV.setText(hourOfDay + "");
                                }

                                if (minute < 10) {
                                    end_minTV.setText("0" + minute);
                                } else {
                                    end_minTV.setText(minute + "");
                                }
                            }
                        };
                TimePickerDialog alert = new TimePickerDialog(getContext(), mTimeSetListener, Integer.parseInt(start_timeTV.getText().toString()), Integer.parseInt(start_minTV.getText().toString()), true);
                alert.setTitle("종료시간 설정");
                alert.show();
            }
        });

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

                int start_time = Integer.parseInt(start_timeTV.getText().toString());
                int start_min = Integer.parseInt(start_minTV.getText().toString());
                int end_time = Integer.parseInt(end_timeTV.getText().toString());
                int end_min = Integer.parseInt(end_minTV.getText().toString());

                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, String> 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());

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

    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;

            } else if (start >= new_s_time && new_e_time >= end) {

                return true;
            }
        }
        return false;
    }
}
