package com.project.ilsaenterprise;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.project.ilsaenterprise.account.UserProfile;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

public class Account extends Fragment {

    private static final String TAG = "Account";
    CardView BtnUpload, BtnList, BtnHistory, BtnFaq;
    Button addButton;
    TextView date, totalPanen, lokasiTph;
    DatabaseReference laporanRef;
    private GoogleSignInAccount googleLogin;
    private FirebaseAuth getmAuth;
    private FirebaseUser userFirebase;
    private String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
    private  DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("users");
    private TextView tvDisplayName, tvIsVerified, tvNotVerified;
    private Boolean isVerified;
    private ConstraintLayout btnVerify, btnLogout, btnEdit;
    private CircleImageView userProfileImage;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_account, container, false);
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

        googleLogin = GoogleSignIn.getLastSignedInAccount(Account.this.getContext());
        getmAuth = FirebaseAuth.getInstance();
        userFirebase = getmAuth.getCurrentUser();
        isVerified = false;

        tvDisplayName = root.findViewById(R.id.tvDisplayName);
        userProfileImage = root.findViewById(R.id.profile_image);
        btnEdit = root.findViewById(R.id.btnProfile);
        tvIsVerified = root.findViewById(R.id.tvEmailVerified);
        tvNotVerified = root.findViewById(R.id.tvEmailNotVerified);
        btnVerify = root.findViewById(R.id.layoutVerify);
        btnLogout = root.findViewById(R.id.btnLogout);
        tvNotVerified.setVisibility(View.GONE);
        tvIsVerified.setVisibility(View.GONE);

        btnVerify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isVerified){
                    Toast.makeText(Account.this.getContext(), "Akun telah terverfikasi.", Toast.LENGTH_LONG).show();
                }
                if(!isVerified){
                    userFirebase.sendEmailVerification()
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Log.d(TAG, "Email dikirim.");
                                        Toast.makeText(Account.this.getContext(), "Email verifikasi dikirim.", Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                }
            }
        });

        btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Account.this.getContext(), UserProfile.class));
            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getmAuth.signOut();
                deleteCache(Account.this.getContext());
                //sharedPreference.saveSPBoolean(SharedPreference.SP_SUDAH_LOGIN, false);
                startActivity(new Intent(Account.this.getContext(), Login.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
            }
        });

        return root;
    }

    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) { e.printStackTrace();}
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            int i = 0;
            while (i < children.length) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
                i++;
            }
        }

        assert dir != null;
        return dir.delete();
    }

    @Override
    public void onStart() {
        super.onStart();

        try{
            reference.child(userFirebase.getUid()).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if((snapshot.exists()) && snapshot.hasChild("namaLengkap") && snapshot.hasChild("image")){
                        tvDisplayName.setText(snapshot.child("namaLengkap").getValue().toString());
                        String retrieveImg = snapshot.child("image").getValue().toString();
                        Picasso.get().load(retrieveImg).placeholder(R.drawable.employee_img).into(userProfileImage);

                        if(userFirebase.isEmailVerified())
                            isVerified = true;
                    }
                    if( (snapshot.exists()) && snapshot.hasChild("namaLengkap") && !snapshot.hasChild("image")){
                        tvDisplayName.setText(snapshot.child("namaLengkap").getValue().toString());
                        Picasso.get().load(userFirebase.getPhotoUrl()).placeholder(R.drawable.employee_img).into(userProfileImage);

                        if(userFirebase.isEmailVerified())
                            isVerified = true;
                    }

                    if(isVerified){
                        tvIsVerified.setVisibility(View.VISIBLE);
                        tvNotVerified.setVisibility(View.INVISIBLE);
                    }
                    if(!isVerified){
                        tvIsVerified.setVisibility(View.INVISIBLE);
                        tvNotVerified.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });
        }catch (Exception e){

        }
    }

    private void getDate(){
        Calendar calDate = Calendar.getInstance();
        SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd MMMM yyyy");
        String currentDate = currentDateFormat.format(calDate.getTime());

        date.setText(currentDate);
    }

}