package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

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.util.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Memo.Login.UserItem;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;

import static android.content.Context.INPUT_METHOD_SERVICE;
import static kr.co.compcarecompany.Activity.ActivityBasic.userItem;

@SuppressLint("ValidFragment")
public class Password_Setting_Fragment extends Fragment {

    Handler handler;
    FragmentActivity fa;
    String machine_pw, type;

    TextView pw_setting_saveTV, pw_setting_guideTV;
    EditText pw_setting_pw1ET, pw_setting_pw2ET, pw_setting_pw3ET, pw_setting_pw4ET;


    @SuppressLint("ValidFragment")
    public Password_Setting_Fragment(Handler handler, String machine_pw) {
        this.handler = handler;
        this.machine_pw = machine_pw;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frg_password_setting, container, false);

        pw_setting_saveTV = v.findViewById(R.id.pw_setting_saveTV);
        pw_setting_guideTV = v.findViewById(R.id.pw_setting_guideTV);
        pw_setting_pw1ET = v.findViewById(R.id.pw_setting_pw1ET);
        pw_setting_pw2ET = v.findViewById(R.id.pw_setting_pw2ET);
        pw_setting_pw3ET = v.findViewById(R.id.pw_setting_pw3ET);
        pw_setting_pw4ET = v.findViewById(R.id.pw_setting_pw4ET);

        init_Handler();
        Set_Contents();
        return v;
    }

    void Set_Contents() {

        //기존 설정한 비밀번호가 없을 때
        if (TextUtils.isEmpty(machine_pw) || machine_pw.equals("")) {
            type = "insert";

            //기존 비밀번호 변경할 경우
        } else {
            type = "update";
        }

        //비밀번호 저장
        pw_setting_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String pw1 = pw_setting_pw1ET.getText().toString();
                String pw2 = pw_setting_pw2ET.getText().toString();
                String pw3 = pw_setting_pw3ET.getText().toString();
                String pw4 = pw_setting_pw4ET.getText().toString();

                if(TextUtils.isEmpty(pw1) || TextUtils.isEmpty(pw2) || TextUtils.isEmpty(pw3) || TextUtils.isEmpty(pw4)){
                    Toast.makeText(getContext(), "숫자를 전부 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(type.equals("update")){

                    pw_setting_pw1ET.getText().clear();
                    pw_setting_pw2ET.getText().clear();
                    pw_setting_pw3ET.getText().clear();
                    pw_setting_pw4ET.getText().clear();

                    if(machine_pw.equals(pw1+pw2+pw3+pw4)){
                        type = "insert";
                        pw_setting_guideTV.setText("새 기계보안 비밀번호를 입력하세요.");
                        pw_setting_guideTV.setTextColor(Color.parseColor("#3a51da"));

                    } else {
                        pw_setting_guideTV.setText("비밀번호가 일치하지 않습니다.");
                        pw_setting_guideTV.setTextColor(Color.RED);
                    }

                    pw_setting_pw1ET.requestFocus();

                }else {

                    //2021.04.05 수정
                    HashMap<String, String> data = new HashMap<>();
                    data.put("mb_id", userItem.getArrayitem().getMbId());
                    data.put("pt_idx", userItem.getArrayitem().getPtIdx());
                    data.put("pt_machine_pw", pw1 + pw2 + pw3 + pw4);
                    new ApiClient(data, "proc_machine_pw_setting2", handler);

                }
            }
        });

        pw_setting_pw1ET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(s.length() > 0){
                    pw_setting_pw2ET.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pw_setting_pw2ET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(s.length() > 0){
                    pw_setting_pw3ET.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pw_setting_pw3ET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(s.length() > 0){
                    pw_setting_pw4ET.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pw_setting_pw4ET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(s.length() > 0){
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //새로운 비밀번호 설정시
        if(type.equals("update")){
            pw_setting_guideTV.setText("기존 비밀번호를 입력하세요.");

        } else {
            pw_setting_guideTV.setText("기계보안 비밀번호를 입력하세요.");
        }
    }

    private void init_Handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                String url = msg.getData().getString("url");

                if (url.equals("proc_machine_pw_setting2")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();

                    if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {

                        userItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<UserItem>>() {
                        }.getType());

                        Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        getActivity().finish();

                    } else {
                        Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
    }
}
