package com.pixelnx.localhelp.ui.login;

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

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.room.Room;

import android.Manifest;
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.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import android.view.View;
import android.widget.RelativeLayout;


import com.pixelnx.localhelp.R;
import com.pixelnx.localhelp.model.ModelUserData;
import com.pixelnx.localhelp.spash.Database;
import com.pixelnx.localhelp.spash.Modellogo;
import com.pixelnx.localhelp.ui.signup.ActivityRegister;
import com.pixelnx.localhelp.ui.vendor.ActivityAllStore;
import com.pixelnx.localhelp.ui.vendor.ActivityVandorDashBoard;
import com.pixelnx.localhelp.utils.Consts;
import com.pixelnx.localhelp.utils.sharedpref.SharedPref;
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.CustomTextExtraBold;

public class ActivityLogin extends Activity implements View.OnClickListener, PreLogin.RegisterInterface,LocationListener {
     CustomTextBold tvCreateOne;
    private CustomTextBold tvAdmin;
    CustomTextExtraBold tvWelcomeText;
    CustomButton btLogin;
    private Context mContext;
    CustomEditText pass;
    CustomEditText  mobile;
    PreLogin preLogin;
    SharedPref sharedPref;
    ModelUserData modelUserData;


    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    Database dataBase;
    Modellogo modellogo;
    RelativeLayout rlForgotPassword;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = ActivityLogin.this;
        sharedPref = SharedPref.getInstance(mContext);


            preLogin = new PreLogin(mContext, this);
            initial();

    }

    private void initial() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            checkLocationPermission();
            }
        tvCreateOne = findViewById(R.id.tvCreateOne);
        btLogin = findViewById(R.id.btLogin);
        rlForgotPassword = findViewById(R.id.rlfp);
        rlForgotPassword.setOnClickListener(this);
        tvAdmin = findViewById(R.id.tvadmin);
        pass = findViewById(R.id.pass);
        mobile = findViewById(R.id.mbl);
        dataBase = Room.databaseBuilder
                (getApplicationContext(),
                        Database.class, "database-name").fallbackToDestructiveMigration()
                .allowMainThreadQueries().build();
        modellogo=new Modellogo();
        modellogo= dataBase.daoAccess().getAllSetData();
        tvWelcomeText = findViewById(R.id.tvWelcomeText);
        if(modellogo != null){
        if(modellogo.getLogoTitle() != null){

           if(!modellogo.getLogoTitle().isEmpty()){
               tvWelcomeText.setText(""+modellogo.getLogoTitle());}
        }}

        tvCreateOne.setOnClickListener(this);
        btLogin.setOnClickListener(this);
    }



    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {


            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                new AlertDialog.Builder(this)
                        .setTitle(R.string.title_location_permission)
                        .setMessage(R.string.text_location_permission)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {


                                ActivityCompat.requestPermissions(ActivityLogin.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);


                            }
                        })
                        .create()
                        .show();


            } else {

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
            assert service != null;
            service.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, (LocationListener) this);



            return true;
        }
    }
    @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);


                }

            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCreateOne:
                boolean gpsEnabled = false;

                LocationManager lm = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
                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();
                }else{
                startActivity(new Intent(mContext, ActivityRegister.class));}
                break;

            case R.id.btLogin:
                if (mobile.getText().toString().length() != 10) {
                    mobile.requestFocus();
                    mobile.setError("Enter correct mobile number.");

                } else {
                    if (pass.getText().toString().length() < 5) {
                        pass.requestFocus();
                        pass.setError("Enter correct password.");


                    } else {
                        preLogin.apiLogin(mobile.getText().toString(), pass.getText().toString());

                    }
                }
                break;
            case R.id.rlfp:
                Intent intent=new Intent(mContext,ActivityForgotPass.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void result(final String result) {
        if(result.contains("Your account has been disabled please contact to admin")){
             tvAdmin.setVisibility(View.VISIBLE);

            tvAdmin.setText(""+result+" click here..");
            tvAdmin.setTextSize(14f);
            tvAdmin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String[] parts = result.split("-");
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:"+parts[1]));
                    startActivity(intent);
                }
            });


        }else {
            sharedPref = SharedPref.getInstance(mContext);
            modelUserData = sharedPref.getUser(Consts.Status.SP);
            if (modelUserData.getData().getUserType().equalsIgnoreCase("3")) {
                Intent intent = new Intent(mContext, ActivityVandorDashBoard.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            } else {
                startActivity(new Intent(mContext, ActivityAllStore.class));
                finish();
            }
        }


    }
    private void exitAppDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("Are you sure you want to close this app?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
    @Override
    public void onBackPressed() {

        exitAppDialog();
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

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

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