package com.pixelnx.localhelp.ui.signup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;


import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import android.os.Bundle;
import android.os.Handler;

import android.provider.Settings;
import android.text.TextUtils;

import android.util.Patterns;
import android.view.View;
import android.widget.LinearLayout;

import android.widget.RadioGroup;
import android.widget.Toast;


import com.google.android.gms.maps.model.LatLng;
import com.pixelnx.localhelp.R;
import com.pixelnx.localhelp.ui.login.ActivityLogin;
import com.pixelnx.localhelp.ui.mapaddress.ActivityMapAddress;

import com.pixelnx.localhelp.utils.widgets.CustomButton;
import com.pixelnx.localhelp.utils.widgets.CustomEditText;
import com.pixelnx.localhelp.utils.widgets.CustomTextBold;
import com.pixelnx.localhelp.utils.widgets.CustomTextViewRegular;

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



public class ActivityRegister extends Activity implements View.OnClickListener, PreRegister.RegisterInterface ,LocationListener{
   CustomTextBold tvAddress;
    CustomEditText etPass;
    CustomEditText etEmail;
    CustomEditText  etDistrict;
    CustomEditText  etWardNum;
    CustomEditText  etTown;
    CustomEditText  etHouse;
    CustomEditText  etMobile;
    CustomEditText   etFullName;
    Context mContext;
    CustomButton btRegister;
    CustomButton btContinue;
    PreRegister preRegister;
    String latitude;
    String  longitude;
    CustomTextViewRegular tvAlreadyAcc;

    RadioGroup rgBtn;

    LinearLayout llUser;
    LinearLayout llReg;
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = ActivityRegister.this;


        LocationManager lm = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
        boolean gpsEnabled = false;

        try {
            assert lm != null;
            gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch(Exception ex) {
            ex.printStackTrace();
        }



        if(!gpsEnabled) {

            new AlertDialog.Builder(mContext)
                    .setMessage(" Activate gps loaction !")
                    .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                            startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);


                        }
                    })
                    .setNegativeButton("no",null)
                    .show();
        }


        initial();
    }




    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_LOCATION) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
                    assert service != null;
                    service.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 , 0, (LocationListener) this);


                }

            }
        }
    }

    private void initial() {

        preRegister = new PreRegister(mContext, this);

        btContinue=findViewById(R.id.btContinue);
        llReg=findViewById(R.id.llReg);
       llUser=findViewById(R.id.lluser);

        rgBtn=findViewById(R.id.rgBtn);


        etPass = findViewById(R.id.passTv);
        tvAlreadyAcc = findViewById(R.id.tvAlreadyAcc);
        tvAlreadyAcc.setOnClickListener(this);
        btContinue.setOnClickListener(this);
        etEmail = findViewById(R.id.emailTv);
        etDistrict = findViewById(R.id.districtTv);
        etWardNum = findViewById(R.id.wardNumTv);
        etTown = findViewById(R.id.towntv);
        etHouse = findViewById(R.id.houseTv);
        etMobile = findViewById(R.id.mobileTv);
        etFullName = findViewById(R.id.fullNameTv);
        new Handler().postDelayed(new Runnable() {


            @Override
            public void run() {


              loc();



            }
        }, 1000);
        tvAddress = findViewById(R.id.tvAddress);
        btRegister = findViewById(R.id.btRegister);

        tvAddress.setOnClickListener(this);
        btRegister.setOnClickListener(this);
    }

    void loc(){
        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        assert service != null;
        @SuppressLint("MissingPermission") Location location = service.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
        LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
            latitude = ""+userLocation.latitude;
            longitude = ""+userLocation.longitude;
            String address="" + latitude + "," + longitude;
            tvAddress.setText(address);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvAddress:
                openLocation();
                break;
            case R.id.btRegister:

                chkAllField();
                break;
            case R.id.tvAlreadyAcc:
                Intent i=new Intent(mContext, ActivityLogin.class);
                startActivity(i);
                break;

        }
    }
    public static boolean isValidEmail(CharSequence target) {
        return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
    }
    void chkAllField() {



        if (etEmail.getText().toString().isEmpty()) {
            etEmail.setError("Enter Email here.");
            etEmail.requestFocus();

        } else {

            if(isValidEmail(""+etEmail.getText().toString())) {
                if (etFullName.getText().toString().isEmpty()) {
                    etFullName.setError("Enter name here!");
                    etFullName.requestFocus();
                } else {
                    if (etMobile.getText().toString().isEmpty()) {
                        etMobile.requestFocus();
                        etMobile.setError("Enter mobile number here!");

                    } else {
                        if (etMobile.getText().toString().length() != 10) {
                            etMobile.requestFocus();
                            etMobile.setError("Mobile number must contain atleast 10 digits.");
                        }else{
                        if (etPass.getText().toString().length() < 5) {
                            etPass.requestFocus();
                            etPass.setError("Password must contain atleast 6 characters.");
                        } else {



                                if (etDistrict.getText().toString().isEmpty() || etWardNum.getText().toString().isEmpty() || etHouse.getText().toString().isEmpty() || etTown.getText().toString().isEmpty()) {
                                    Toast.makeText(mContext, "All Field Required!", Toast.LENGTH_SHORT).show();
                                } else {



                                        preRegister.apiRegister("" + etEmail.getText().toString(), "" + etFullName.getText().toString(), "" + etMobile.getText().toString(),
                                                "" + etPass.getText().toString(),
                                                "" + etDistrict.getText().toString() + "|" + etWardNum.getText().toString() + "|" + etTown.getText().toString()
                                                        + "|" + etHouse.getText().toString(), ""+latitude, ""+longitude);

                                }

                        }
                    }}

                }
            }else{
                etEmail.requestFocus();
                etEmail.setError("Enter Valid Email.");
            }
        }


    }

    private void openLocation() {
        loc();

        Intent intent = new Intent(this, ActivityMapAddress.class);
        startActivityForResult(intent, 10001);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == RESULT_OK) {


                if (requestCode == 10001) {


                    assert data != null;
                    tvAddress.setText(data.getStringExtra("city"));
                    latitude = "" + data.getStringExtra("lati");
                    longitude = "" + data.getStringExtra("long");

                }


        }







    }





    @Override
    public void result(String res) {
        try {
            JSONObject data =new JSONObject(res);


            Intent intent=new Intent(mContext,ActivityOtp.class);
            intent.putExtra("mbl",""+data.getString("userMobile"));
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }




    }

    @Override
    public void onLocationChanged(Location location) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onProviderEnabled(String s) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void onProviderDisabled(String s) {
        throw new UnsupportedOperationException();
    }
}
