package kr.co.icontrols.iotplatform;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import kr.co.icontrols.iotplatform.utils.HttpApi;
import kr.co.icontrols.iotplatform.utils.SharedPrefUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.PopupActivity.DEFAULT_POPUP_TIMEOUT;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ForceDismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.WarnLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_CONFIRM_SEND_INVITE_MSG;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INIT_APP_CONFIRM;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_LOGOUT_SUCCESS;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_NO_CONTENT;

public class InviteMemberInputActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "InviteMemberInputActivity";

    private String mMode;
    private String mValue = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_member_input);

        Intent intent = getIntent();
        mMode = intent.getStringExtra("MODE");
        if(mMode.equals("email")) {
            ((TextView) findViewById(R.id.txtSubscription1)).setText(getString(R.string.activity_invite_member_input_text_email));
            ((EditText)findViewById(R.id.txtInput)).setHint("abcde@abcde.com");
        } else if(mMode.equals("phone")) {
            ((TextView) findViewById(R.id.txtSubscription1)).setText(getString(R.string.activity_invite_member_input_text_phone));
            ((EditText)findViewById(R.id.txtInput)).setHint("01012341234");
        } else {
            finish();
        }
    }

    @Override
    protected void onPause() {
        ForceDismissConnectDialog();
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        /*
        final View fv = v;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);
        */

        switch (v.getId()) {
            case R.id.btnBack:
                onBackPressed();
                break;
            case R.id.btnRight:
                mValue = ((EditText)findViewById(R.id.txtInput)).getText().toString();
                //TODO - 유효성 검사 필요함.
                if(mValue.length()==0) {
                    Intent intent = new Intent(this, PopupActivity.class);
                    intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_NORMAL);
                    if(mMode.equals("email")) {
                        intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.popup_input_email));
                    } else {
                        intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.popup_input_phone_number));
                    }
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(this, PopupActivity.class);
                    intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_YESNO);
                    if(mMode.equals("email")) {
                        intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.popup_confirm_send_invite_email));
                    } else {
                        intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.popup_confirm_send_invite_sms));
                    }
                    startActivityForResult(intent, RESULT_CONFIRM_SEND_INVITE_MSG);
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_CONFIRM_SEND_INVITE_MSG:
                if (resultCode == Activity.RESULT_OK) {
                    try {
                        displayProgress(this,"","");
                        if(mMode.equals("email")) {
                            HttpApi.inviteGuestForMaster(true, mValue, mInviteGuestCallback);
                        } else {
                            HttpApi.inviteGuestForMaster(false, mValue, mInviteGuestCallback);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ErrorLogOutput(TAG, "HttpApi.inviteGuestForMaster(Exception)\n" + e.toString());
                        showNotiMsg(InviteMemberInputActivity.this, "맴버 초대를 실패하였습니다.");
                        DismissConnectDialog();
                    }
                }
                break;
        }
    }

    Callback mInviteGuestCallback = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.inviteGuestForMaster(onFailure)\n" + e.toString());
            DismissConnectDialog();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(response.code() == HTTP_NO_CONTENT) {
                WarnLogOutput(TAG, "HttpApi.inviteGuestForMaster(onResponse) Status code : " + response.code());
                String msg = "";
                if(mMode.equals("email")) {
                    msg = "초대 이메일이 발송되었습니다";
                } else {
                    msg = "초대 문자가 발송되었습니다";
                }
                showNotiMsg(InviteMemberInputActivity.this,msg,AdminMemberActivity.class,Intent.FLAG_ACTIVITY_CLEAR_TOP);
                DismissConnectDialog();
            } else {
                ErrorLogOutput(TAG, "HttpApi.inviteGuestForMaster(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                showNotiMsg(InviteMemberInputActivity.this, "맴버 초대를 실패하였습니다.");
                DismissConnectDialog();
                try {
                    JSONObject json_data = new JSONObject(response.body().string());
                    ErrorLogOutput(TAG, "HttpApi.inviteGuestForMaster(onResponse) body : " + json_data.toString());
                } catch (JSONException e) {
                    ErrorLogOutput(TAG, "HttpApi.inviteGuestForMaster(onResponse) JSONException : " + e.toString());
                }
            }
        }
    };
}