package kr.co.compcarecompany.Fragment.Join;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.GMailSender;

public class Find_Password_Fragment extends Fragment {

    private Handler handler;
    TextView checkTV, loginTV;
    EditText mb_idET, mb_emailET;
    FragmentActivity fa;

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

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

    @SuppressLint("ValidFragment")
    public Find_Password_Fragment(Handler handler) {
        this.handler = handler;
     }

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

        checkTV = v.findViewById(R.id.checkTV);
        loginTV = v.findViewById(R.id.loginTV);
        mb_idET = v.findViewById(R.id.mb_idET);
        mb_emailET = v.findViewById(R.id.mb_emailET);

        init_Handler();
        init_Listener();

        return v;
    }

    public void postToastMessage(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
                loginTV.setVisibility(View.VISIBLE);
                checkTV.setVisibility(View.GONE);
            }
        });
    }

    void init_Listener() {

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

                String mb_id = mb_idET.getText().toString();
                String mb_email = mb_emailET.getText().toString();

                if (TextUtils.isEmpty(mb_id) || TextUtils.isEmpty(mb_email)) {
                    Common.getInstance().toastShow(getContext(), "아이디와 이메일을 전부 입력해주세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("mb_id", mb_id);
                data.put("mb_email", mb_email);
                new ApiClient(data, "proc_admin_check_member", handler);

                Toast.makeText(getContext(), "아이디와 이메일을 확인하고 있습니다.\n잠시 기다려주세요.", Toast.LENGTH_LONG).show();
            }
        });

        loginTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fa.finish();
            }
        });
    }

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

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

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

                            GMailSender sender = new GMailSender("yjbyun8@gmail.com", "dbswjd11!!");

                            new Thread(new Runnable() {
                                public void run() {
                                    // TODO Auto-generated method stub
                                    String msg = sender.sendMail("임시 비밀번호 발송", "요청하신 아이디의 임시 비밀번호는 " + sender.getEmailCode() + " 입니다.\n로그인 후 비밀번호를 반드시 변경해주세요.", "holic0130@naver.com");
                                    postToastMessage(msg);

                                    if (msg.contains("발송되었습니다")) {
                                        HashMap<String, String> data = new HashMap<>();
                                        data.put("mb_id", mb_idET.getText().toString());
                                        data.put("mb_password", sender.getEmailCode());
                                        new ApiClient(data, "proc_admin_set_temp_password", handler);
                                    }
                                }
                            }).start();

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

}

