package com.tsi.navi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.tsi.navi.databinding.ActivityRegisterBinding;
import com.tsi.navi.util.BackPressedForFinish;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterActivity extends AppCompatActivity {
    private static final String TAG = RegisterActivity.class.getSimpleName();

    private BackPressedForFinish backPressedForFinish;
    private ActivityRegisterBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(this.binding.getRoot());

        this.backPressedForFinish = new BackPressedForFinish(this);

        final EditText deviceIdText = this.binding.edDeviceId;
        this.binding.login.setEnabled(true);

        deviceIdText.setText(getIntent().getStringExtra("deviceId").toString());

        // 전화번호에 '-' 추가해서 표출하기
        //binding.edPhone.setText(PhoneNumberUtils.formatNumber("01012341234", Locale.getDefault().getCountry()));
        // 연락처 입력시 하이픈(-) 자동 입력.
        //binding.edPhone.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

        this.binding.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String company = binding.edCompany.getText().toString().trim();
                String manager = binding.edManager.getText().toString().trim();
                String phone = binding.edPhone.getText().toString().trim();
                String email = binding.edEmail.getText().toString().trim();

                if (company.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "업체명을 입력하세요.", Toast.LENGTH_LONG).show();
                    return;
                }
                if (manager.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "담당자를 입력하세요.", Toast.LENGTH_LONG).show();
                    return;
                }
                if (phone.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "핸드폰번호를 입력하세요.", Toast.LENGTH_LONG).show();
                    return;
                }
                else {
                    if (phone.length() != 11) {
                        Toast.makeText(getApplicationContext(), "핸드폰번호를 확인하세요.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    phone = phoneNumberSplit(phone);
                    if (!isValidCellPhoneNumber(phone)) {
                        Toast.makeText(getApplicationContext(), "핸드폰번호를 확인하세요.", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                if (email.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "이메일을 입력하세요.", Toast.LENGTH_LONG).show();
                    return;
                }
                else {
                    Pattern pattern = Patterns.EMAIL_ADDRESS;
                    if (!pattern.matcher(email).matches()) {
                        Toast.makeText(getApplicationContext(), "이메일을 형식이 맞지 않습니다.", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                Intent intent = new Intent();
                intent.putExtra("dialogType", InitActivity.REGISTER_DEVICE_CODE);
                intent.putExtra("company", company);
                intent.putExtra("manager", manager);
                intent.putExtra("phone", phone);
                intent.putExtra("email", email);

                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        binding.btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityCompat.finishAffinity(RegisterActivity.this);
                System.exit(0);
            }
        });
    }
    public String phoneNumberSplit(String phoneNumber) {

        Pattern tellPattern = Pattern.compile( "^(01\\d{1}|02|0505|0502|0506|0\\d{1,2})-?(\\d{3,4})-?(\\d{4})");

        Matcher matcher = tellPattern.matcher(phoneNumber);
        if (matcher.matches()) {
            //정규식에 적합하면 matcher.group으로 리턴
            return matcher.group(1) + "-" + matcher.group(2) + "-" + matcher.group(3);
        }
        else {
            //정규식에 적합하지 않으면 substring 으로 휴대폰 번호 나누기
            String str1 = phoneNumber.substring(0, 3);
            String str2 = phoneNumber.substring(3, 7);
            String str3 = phoneNumber.substring(7, 11);
            return str1 + "-" + str2 + "-" + str3;
        }
    }

    public boolean isEmail(String email) {

        if (email==null) return false;
        boolean b = Pattern.matches("[\\w\\~\\-\\.]+@[\\w\\~\\-]+(\\.[\\w\\~\\-]+)+", email.trim());
        return b;

    }

    public boolean validPhoneNumber(String number) {
        Pattern pattern = Pattern.compile("\\d{3}-\\d{4}-\\d{4}");
        Matcher matcher = pattern.matcher(number);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isValidCellPhoneNumber(String cellphoneNumber) {

        boolean returnValue = false;
        try {
            String regex = "^\\s*(010|011|016|017|018|019)(-|\\)|\\s)*(\\d{3,4})(-|\\s)*(\\d{4})\\s*$";

            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(cellphoneNumber);
            if (m.matches()) {
                returnValue = true;
            }

            if (returnValue && cellphoneNumber != null
                    && cellphoneNumber.length() > 0
                    && cellphoneNumber.startsWith("010")) {
                cellphoneNumber = cellphoneNumber.replace("-", "");
                if (cellphoneNumber.length() != 11) {
                    returnValue = false;
                }
            }
            return returnValue;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean isValidPhoneNumber(String phoneNumber) {
        String regex = "^\\s*(02|031|032|033|041|042|043|051|052|053|054|055|061|062|063|064|070)?(-|\\)|\\s)*(\\d{3,4})(-|\\s)*(\\d{4})\\s*$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phoneNumber);
        return m.matches();
    }

    @Override
    public void onBackPressed() {
        backPressedForFinish.onBackPressed(true);
    }

/*
    //이메일형식체크
    if(!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches())
    {
        Toast.makeText(SignupActivity.this,"이메일 형식이 아닙니다",Toast.LENGTH_SHORT).show();
        return;
    }
    //핸드폰번호 유효성
    if(!Pattern.matches("^01(?:0|1|[6-9]) - (?:\\d{3}|\\d{4}) - \\d{4}$", Phone_num))
    {
        Toast.makeText(SignupActivity.this,"올바른 핸드폰 번호가 아닙니다.",Toast.LENGTH_SHORT).show();
        return;
    }
    //비밀번호 유효성
    if(!Pattern.matches("^(?=.*\\d)(?=.*[~`!@#$%\\^&*()-])(?=.*[a-zA-Z]).{8,20}$", PW))
    {
        Toast.makeText(SignupActivity.this,"비밀번호 형식을 지켜주세요.",Toast.LENGTH_SHORT).show();
        return;
    }
*/

}