package com.example.floatinglabel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.strictmode.WebViewMethodCalledOnWrongThreadViolation;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.zip.Inflater;

public class MainActivity extends AppCompatActivity {
  EditText Name, email, Password;
  TextInputLayout namelayout, emaillayout, passwordlayout;
    Button btn, imgbtn;
    Uri fileData;
    ProgressDialog progressDialog;
    FirebaseAuth auth;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==01 && resultCode==RESULT_OK){
            fileData=data.getData();
        }

    }

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

        Name=findViewById(R.id.edt1);
        email=findViewById(R.id.edt2);
        Password=findViewById(R.id.edt3);
        namelayout=findViewById(R.id.namelayout);
        emaillayout=findViewById(R.id.emaillayout);
        passwordlayout=findViewById(R.id.passlayout);
        btn=findViewById(R.id.button);
        imgbtn=findViewById(R.id.imageButton);
        progressDialog=new ProgressDialog(this);


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitform();
            }
        });
        imgbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(intent,01);
                }
            });
    }
    private void submitform() {
        final String UserEmail= email.getText().toString().trim();
        final String Username=Name.getText().toString().trim();
        final String Userpass=Password.getText().toString().trim();
        if(!validatename()){
            return;
        }
        if(!validateemail()){
            return;
        }
        if(!validatepassword()){
            return;
        }
        InsertData(Username,UserEmail,Userpass,fileData);
    }

    private void InsertData(final String name, final String email, final String password, final Uri fileData) {
    progressDialog.setMessage("plz wait...");
    progressDialog.setCancelable(false);
    progressDialog.show();

    auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful()){
                SendImage(name,email,password,fileData);
            }
            else
            {
                Toast.makeText(getApplicationContext(), "authentican not done", Toast.LENGTH_SHORT).show();
            }
        }
    });



    }

    private void SendImage(final String name, final String email, final String password, final Uri fileData) {
        final StorageReference ref= FirebaseStorage.getInstance().getReference("Image/"+auth.getCurrentUser().getUid());
        ref.putFile(fileData).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if(task.isSuccessful()){
                   throw task.getException();
                }
                return ref.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if(task.isSuccessful()){
                    Uri Downloadurl=task.getResult();
                    InsertRealtimeDataBase(name,email,password,fileData);
                }else
                {   progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "task not sucessful", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

    private void InsertRealtimeDataBase(String name, String email, String password, Uri fileData) {

       Model val=new Model(name, email,  password, fileData);

        FirebaseDatabase.getInstance().getReference("Person").child(auth.getCurrentUser().getUid()).setValue(val).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()){
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "data entered", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "no data entered", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

    private boolean validatepassword() {
        if(Password.getText().toString().trim().isEmpty() && Password.getText().toString().length()<8){
            passwordlayout.setError("Enter password");
            requestFocus(Password);
            return false;
        }
        else
        {
            passwordlayout.setEnabled(false);
        }
        return true;
    }

    private void requestFocus(View view) {
        if (view.requestFocus()){
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private boolean validateemail() {
       String Email= email.getText().toString().trim();
        if(Email.isEmpty() && !Emailmatching(Email)){
            emaillayout.setError("Enter valid Email");
            requestFocus(email);
            return false;
        }
        else
        {
            emaillayout.setEnabled(false);
        }
        return true;

    }

    private boolean Emailmatching(String email) {
        return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
// trim white space ko remove
    private boolean validatename() {
        if(Name.getText().toString().trim().isEmpty()){
            namelayout.setError("Enter name please");
            requestFocus(Name);
            return false;
        }
        else
        {
            namelayout.setEnabled(false);
        }
        return true;
    }
}



