package kr.co.compcareworker.Util.CustomView;

import android.app.DatePickerDialog;
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.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.Data.Company.Machine.Product.ProductData;
import kr.co.compcareworker.Data.MainViewList.SubProdData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

public class RunningTimeResetDialog extends Dialog {

    private Context context;
    private Handler hdr;
    private TextView reset_dateTV, closeTV, running_time_resetTV, running_timeTV, cycleTV, running_time_modifyTV, cycle_modifyTV;
    private LinearLayout reset_dateLL;
    private DatePickerDialog.OnDateSetListener callbackMethod;
    private MachineItem item;
    private EditText cycleET, running_timeET;

    public RunningTimeResetDialog(@NonNull Context context, Handler hdr, MachineItem item) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.item = item;
    }

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

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

        reset_dateLL = findViewById(R.id.reset_dateLL);
        reset_dateTV = findViewById(R.id.reset_dateTV);
        running_timeTV = findViewById(R.id.running_timeTV);
        cycleTV = findViewById(R.id.cycleTV);
        closeTV = findViewById(R.id.closeTV);
        running_time_resetTV = findViewById(R.id.running_time_resetTV);
        cycleET = findViewById(R.id.cycleET);
        running_timeET = findViewById(R.id.running_timeET);
        running_time_modifyTV = findViewById(R.id.running_time_modifyTV);
        cycle_modifyTV = findViewById(R.id.cycle_modifyTV);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.KOREA);
        String today =  dataFormat.format(calendar.getTime());

        reset_dateTV.setText(today);
        if(item.getMcRunningtime() != null) {
            running_timeTV.setText(item.getMcRunningtime());
        } else {
            running_timeTV.setText("0");
        }

        if(item.getMcCycle() != null) {
            cycleTV.setText(item.getMcCycle());
        } else {
            cycleTV.setText("0");
        }

        init_Handler();
        init_Listener();
    }

    void init_Listener() {

        //날짜 선택 클릭리스너
        reset_dateLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Calendar date = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getContext(), callbackMethod, date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DAY_OF_MONTH));
                dialog.getDatePicker().setMaxDate(date.getTimeInMillis());
                date.set(Calendar.YEAR, Calendar.YEAR - 1);
                dialog.getDatePicker().setMinDate(date.getTimeInMillis());
                dialog.show();
            }
        });

        //사용시간 수정버튼 클릭리스너
        running_time_modifyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (running_time_modifyTV.getText().equals("수정")) {
                    running_timeET.setVisibility(View.VISIBLE);
                    running_timeTV.setVisibility(View.GONE);
                    running_time_modifyTV.setText("취소");
                    running_time_modifyTV.setBackgroundResource(R.drawable.bg_round_gray);
                } else {
                    running_timeET.setVisibility(View.GONE);
                    running_timeTV.setVisibility(View.VISIBLE);
                    running_time_modifyTV.setText("수정");
                    running_time_modifyTV.setBackgroundResource(R.drawable.bg_round_main);
                }
            }
        });

        //만료시간 수정버튼 클릭리스너
        cycle_modifyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cycle_modifyTV.getText().equals("수정")) {
                    cycleET.setVisibility(View.VISIBLE);
                    cycleTV.setVisibility(View.GONE);
                    cycle_modifyTV.setText("취소");
                    cycle_modifyTV.setBackgroundResource(R.drawable.bg_round_gray);
                } else {
                    cycleET.setVisibility(View.GONE);
                    cycleTV.setVisibility(View.VISIBLE);
                    cycle_modifyTV.setText("수정");
                    cycle_modifyTV.setBackgroundResource(R.drawable.bg_round_main);
                }
            }
        });

        //닫기 버튼 클릭리스너
        closeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        //초기화 버튼 클릭리스너
        running_time_resetTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String running_time = "";
                String cycle = "";

                if (running_time_modifyTV.getText().equals("취소")) {
                    running_time = running_timeET.getText().toString();

                    if(TextUtils.isEmpty(running_time)){
                        Common.getInstance().toastShow(context, "사용시간을 입력해주세요.");
                        return;
                    }
                }

                if (cycle_modifyTV.getText().equals("취소")) {
                    cycle = cycleET.getText().toString();

                    if(TextUtils.isEmpty(cycle)){
                        Common.getInstance().toastShow(context, "만료시간을 입력해주세요.");
                        return;
                    }
                }

                //reset api 호출
                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", item.getAgIdx());
                data.put("mc_idx", item.getMcIdx());
                data.put("pd_idx", item.getPdIdx());
                data.put("mc_runningtime_total", running_time);
                data.put("mc_cycle", cycle);
                data.put("mc_exchangedt", reset_dateTV.getText().toString());
                new ApiClient(data, "proc_running_time_reset", hdr);
            }
        });

        callbackMethod = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                int month = monthOfYear + 1;
                String con_month = month + "";
                if (month < 10) {
                    con_month = "0" + con_month;
                }

                String con_day = dayOfMonth + "";
                if (dayOfMonth < 10) {
                    con_day = "0" + con_day;
                }
                reset_dateTV.setText(year + "-" + con_month + "-" + con_day);
            }
        };

    }

    void init_Handler() {

        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) {

                    if (url.equals("proc_running_time_reset")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        Log.d("초기화@@@@", result_item.toString());
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Common.getInstance().toastShow(context, "초기화를 성공했습니다.");
                            dismiss();
                        }else {
                            Common.getInstance().toastShow(context, "초기화를 실패했습니다. 다시 시도해주세요.");
                        }
                    }

                } else if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }
}

