package dev.android.example.jobland.fragments;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
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 java.util.ArrayList;
import java.util.List;

import dev.android.example.jobland.R;
import dev.android.example.jobland.activities.AddJobActivity;
import dev.android.example.jobland.activities.EditJobActivity;
import dev.android.example.jobland.activities.UpdateEmployerInfoActivity;
import dev.android.example.jobland.adapters.JobAdapter;
import dev.android.example.jobland.models.Employer;
import dev.android.example.jobland.models.Job;
import dev.android.example.jobland.models.User;

/**
 * A simple {@link Fragment} subclass.
 */
public class JobManagerFragment extends Fragment {

    private List<Job> list;
    private JobAdapter jobAdapter;
    private RecyclerView rv_joblist;
    private FirebaseDatabase database;
    private DatabaseReference myRef, node_store, node_user;
    private int pos;
    private FirebaseAuth mAuth;
    private FloatingActionButton fab;
    private RecyclerView rv_job_manager;

    public JobManagerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_job_manager, container, false);
        fab = (FloatingActionButton) rootView.findViewById(R.id.floatingActionButton);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext(), AddJobActivity.class);
                startActivity(i);
            }
        });
        list = new ArrayList<Job>();
        rv_joblist = (RecyclerView) rootView.findViewById(R.id.rv_jobman_recycler);
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference("Jobs");
        node_store = database.getReference("Employers");
        node_user = database.getReference("Users");

        node_user.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user.getAccountType() == 0) {
                    new AlertDialog.Builder(getActivity(), R.style.AlertDialogCustom)
                            .setMessage("CREATE A NEW PROFILE STORE ?")
                            .setPositiveButton("Create new", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    startActivity(new Intent(getActivity(), UpdateEmployerInfoActivity.class));
                                    getActivity().finish();
                                }
                            }).setCancelable(false).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        jobAdapter = new JobAdapter(getContext(), list);
        list.clear();
        node_user.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                if (user != null && user.getAccountType() == 1) {
                    final String store_key = user.getId();
                    node_store.child(store_key).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            final Employer store = dataSnapshot.getValue(Employer.class);
                            if (store != null) {
                                myRef.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {
                                        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                                            Job job = postSnapshot.getValue(Job.class);
                                            if (job != null && job.getEmployerName().equals(store_key)) {
                                                list.add(job);
                                                jobAdapter.notifyDataSetChanged();
                                            }
                                        }
                                        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);

                                        rv_joblist.setLayoutManager(layoutManager);
                                        rv_joblist.setItemAnimator(new DefaultItemAnimator());
                                        rv_joblist.setAdapter(jobAdapter);
                                    }

                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {

                                    }
                                });
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                } else {
//                    startActivity(new Intent(getActivity(), UpdateEmployerInfoActivity.class));
//                    getActivity().finish();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return rootView;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        pos = item.getOrder();
        switch (item.getItemId()) {
            case 0:
                Intent intent = new Intent(getContext(), EditJobActivity.class);
                intent.putExtra("ID_JOB", list.get(pos).getId());
                startActivity(intent);
                return true;
            case 1:
                delete(list.get(pos).getId());
                return true;
            default:
                return false;
        }
    }

    public void delete(final String id) {
        AlertDialog.Builder bui = new AlertDialog.Builder(getContext());
        bui.setMessage("Do you want to delete this job?");

        bui.setPositiveButton("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        bui.setNegativeButton("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                myRef.child(id).setValue(null);
                list.clear();
                jobAdapter.notifyDataSetChanged();
                Toast.makeText(getActivity(), "Delete data successfully!", Toast.LENGTH_LONG).show();
            }
        });
        bui.show();
    }

}
