package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.security.NoSuchAlgorithmException;
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 kr.co.compcarecompany.Util.Common;

import static kr.co.compcarecompany.Activity.ActivityBasic.userItem;

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

    Handler handler;
    FragmentActivity fa;

    TextView info_pwTV, info_pw_checkTV, info_modifyTV, info_cancelTV, info_saveTV;
    EditText info_idET, info_pwET, info_pw_checkET, info_nameET, info_phoneET, info_emailET;
    ImageView info_pw_cancelIV, info_pw_check_cancelIV, info_name_cancelIV, info_phone_cancelIV, info_email_cancelIV;
    LinearLayout info_pwLL;
    String mb_id, mb_password;

    public Member_Info_Fragment(Handler handler) {
        this.handler = handler;
    }

    @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.frag_member_info, container, false);

        info_idET = v.findViewById(R.id.info_idET);

        info_pwLL = v.findViewById(R.id.info_pwLL);
        info_pwET = v.findViewById(R.id.info_pwET);
        info_pwTV = v.findViewById(R.id.info_pwTV);
        info_pw_cancelIV = v.findViewById(R.id.info_pw_cancelIV);
        info_pw_checkET = v.findViewById(R.id.info_pw_checkET);
        info_pw_check_cancelIV = v.findViewById(R.id.info_pw_check_cancelIV);
        info_pw_checkTV = v.findViewById(R.id.info_pw_checkTV);

        info_nameET = v.findViewById(R.id.info_nameET);
        info_name_cancelIV = v.findViewById(R.id.info_name_cancelIV);

        info_phoneET = v.findViewById(R.id.info_phoneET);
        info_phone_cancelIV = v.findViewById(R.id.info_phone_cancelIV);

        info_emailET = v.findViewById(R.id.info_emailET);
        info_email_cancelIV = v.findViewById(R.id.info_email_cancelIV);

        info_modifyTV = v.findViewById(R.id.info_modifyTV);
        info_cancelTV = v.findViewById(R.id.info_cancelTV);
        info_saveTV = v.findViewById(R.id.info_saveTV);

        info_pwLL.setVisibility(View.GONE);
        info_name_cancelIV.setVisibility(View.GONE);
        info_phone_cancelIV.setVisibility(View.GONE);
        info_email_cancelIV.setVisibility(View.GONE);
        info_modifyTV.setVisibility(View.VISIBLE);
        info_cancelTV.setVisibility(View.GONE);
        info_saveTV.setVisibility(View.GONE);

        info_pwET.setEnabled(false);
        info_nameET.setEnabled(false);
        info_phoneET.setEnabled(false);
        info_emailET.setEnabled(false);


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

    void Set_Contents() {

        info_idET.setText(fa.userItem.getArrayitem().getMbId());
        info_nameET.setText(fa.userItem.getArrayitem().getMbName());
        info_phoneET.setText(fa.userItem.getArrayitem().getMbPhone());
        info_emailET.setText(fa.userItem.getArrayitem().getMbEmail());

    }

    void init_Listener() {

        //이름 텍스트 지우기
        info_name_cancelIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                info_nameET.getText().clear();
            }
        });

        //연락처 텍스트 지우기
        info_phone_cancelIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                info_phoneET.getText().clear();
            }
        });

        //이메일 텍스트 지우기
        info_email_cancelIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                info_emailET.getText().clear();
            }
        });

        //연락처 자동으로 - 생성
        info_phoneET.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

        //비밀번호 체크
        info_pwET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (Common.getInstance().validationPassword(charSequence.toString())) {
                    info_pwTV.setText("**사용 가능한 비밀번호 입니다.**");
                    info_pwTV.setTextColor(getContext().getResources().getColor(R.color.green));

                    info_pw_checkET.setEnabled(true);
                } else {
                    info_pwTV.setText("**비밀번호는 문자, 숫자, 특수문자를 포함한 8자리 이상으로 입력해주세요.**");
                    info_pwTV.setTextColor(getContext().getResources().getColor(R.color.red));
                    info_pw_checkET.setEnabled(false);
                }

                if (charSequence.length() < 1) {
                    info_pwTV.setText("**비밀번호는 영문, 특수문자, 숫자 포함 8자 이상 입력하세요.");
                    info_pwTV.setTextColor(getContext().getResources().getColor(R.color.black));
                    info_pw_checkET.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        //비밀번호 확인 체크
        info_pw_checkET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String pw = info_pwET.getText().toString();
                String pw_chk = info_pw_checkET.getText().toString();

                if (!TextUtils.isEmpty(pw) && !TextUtils.isEmpty(pw_chk) && pw.equals(pw_chk)) {
                    info_pw_checkTV.setText("**비밀번호가 일치합니다.**");
                    info_pw_checkTV.setTextColor(getContext().getResources().getColor(R.color.green));
                } else {
                    info_pw_checkTV.setText("**비밀번호가 일치하지 않습니다.**");
                    info_pw_checkTV.setTextColor(getContext().getResources().getColor(R.color.red));
                }

                if (pw_chk.isEmpty()) {
                    info_pw_checkTV.setText("**비밀번호를 한 번 더 입력하세요**");
                    info_pw_checkTV.setTextColor(getContext().getResources().getColor(R.color.black));
                }
            }
        });


        //정보 수정 버튼 클릭 리스너
        info_modifyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                info_pwLL.setVisibility(View.VISIBLE);
                info_name_cancelIV.setVisibility(View.VISIBLE);
                info_phone_cancelIV.setVisibility(View.VISIBLE);
                info_email_cancelIV.setVisibility(View.VISIBLE);
                info_modifyTV.setVisibility(View.GONE);
                info_cancelTV.setVisibility(View.VISIBLE);
                info_saveTV.setVisibility(View.VISIBLE);

                info_pwET.setEnabled(true);
                info_nameET.setEnabled(true);
                info_phoneET.setEnabled(true);
                info_emailET.setEnabled(true);
            }
        });

        //취소 버튼 클릭 리스너
        info_cancelTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                info_pwLL.setVisibility(View.GONE);
                info_name_cancelIV.setVisibility(View.GONE);
                info_phone_cancelIV.setVisibility(View.GONE);
                info_email_cancelIV.setVisibility(View.GONE);
                info_modifyTV.setVisibility(View.VISIBLE);
                info_cancelTV.setVisibility(View.GONE);
                info_saveTV.setVisibility(View.GONE);

                info_pwET.setEnabled(false);
                info_nameET.setEnabled(false);
                info_phoneET.setEnabled(false);
                info_emailET.setEnabled(false);

                Set_Contents();
            }
        });

        //저장 버튼 클릭 리스너
        info_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mb_id = info_idET.getText().toString();
                String mb_name = info_nameET.getText().toString();
                String mb_pw = info_pwET.getText().toString();
                String mb_phone = info_phoneET.getText().toString();
                String mb_email = info_emailET.getText().toString();

                if (TextUtils.isEmpty(mb_id) || TextUtils.isEmpty(mb_name) || TextUtils.isEmpty(mb_pw) || TextUtils.isEmpty(mb_phone) || TextUtils.isEmpty(mb_email)) {
                    Common.getInstance().toastShow(getContext(), "정보 칸을 전부 입력해주세요.");
                    return;
                }

                //연락처 체크
                if (mb_phone.length() > 16) {
                    Common.getInstance().toastShow(getContext(), "전화번호 형식이 올바르지 않습니다.");
                    return;
                }

                //이메일 체크
                if (!Common.getInstance().isValidEmail(mb_email)) {
                    Common.getInstance().toastShow(getContext(), "이메일 형식이 올바르지 않습니다.");
                    return;
                }

                String[] encrypt_pw = new String[0];

                try {
                    encrypt_pw = Common.getInstance().encrypt(mb_pw);

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }

                mb_password = encrypt_pw[0];

                HashMap<String, String> data = new HashMap<>();
                data.put("mb_type", "COMPANY");
                data.put("mb_id", mb_id);
                data.put("mb_name", mb_name);
                data.put("mb_phone", mb_phone);
                data.put("mb_email", mb_email);
                data.put("mb_password", mb_password);
                data.put("mb_salt", encrypt_pw[1]);
                Log.d("데이터@@@", data.toString());
                new ApiClient(data, "proc_member_info_modify", handler);


            }
        });

    }

    private void init_Handler() {
        handler = 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_member_info_modify")) {
                        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")) {

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

                            Common.getInstance().setPref(getContext(), "id", mb_id);
                            Common.getInstance().setPref(getContext(), "pw", mb_password);

                            Log.d("새아디비번", "아이디 : "+Common.getInstance().getPref(getContext(),"id")+" 비번 : "+Common.getInstance().getPref(getContext(),"pw"));

                            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();
                        }
                    }
                } else if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }

            }
        };
    }
}
