package com.grewe.ilab.firebaseapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity {

    //this represents object to access FirebaseDatbase associated with this app
    FirebaseDatabase mFirebaseDatabase;

    //this represents object to access the Items part of the datbase
    DatabaseReference mItemsDatabase;

    //button for entering item into database
    Button mStoreButton;

    //item name Edit Text and quantity quantity_EditText
    EditText item_EditText;
    EditText quantity_EditText;

    // items ListView of what is currently in the database
    ListView items_ListView;

    //Adapter for items_ListView
    ItemsAdapter itemsAdapter;

    //child event listener to get read/updates automatically from Firebase items database
    ChildEventListener items_childEventListener;


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


        // [START initialize_database_ref]
        //grab handle to FirebaseDatabase
        mFirebaseDatabase = FirebaseDatabase.getInstance();

        //grab handle to the items "table" portion of our JSON tree that is the databse
        mItemsDatabase = mFirebaseDatabase.getReference().child("items");
        // [END initialize_database_ref]



        //grab handles to edit texts for item name and quantity
        item_EditText = (EditText) findViewById(R.id.item_TextView);
        quantity_EditText = (EditText) findViewById(R.id.quantity_editText2);

        //grab handle to the ListView that will populate with the current Firebase items database
        items_ListView = (ListView) findViewById(R.id.itemsListView);


        //grab handle to the button
        mStoreButton = (Button) findViewById(R.id.buttonStore);



        //initialize List and Adapter for our items_ListView
        List<Item> listItems = new ArrayList<>();
        // create adapter where each item's layout specified by item_layout.xml and use listItems to populate List View
        itemsAdapter = new ItemsAdapter(this, R.layout.item_layout ,listItems );
        //now register adapter to the list view
        items_ListView.setAdapter(itemsAdapter);




        //register event handler for the Store button
        // Send button sends a message and clears the EditText
        mStoreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // crete instance of the Item class based on user input data
                Item item = new Item(item_EditText.getText().toString(), quantity_EditText.getText().toString());

                //store to our database -- note the push method will in essence execute
                //   mItemsDatabase.child(itemId).setValue(item);  and create the itemID for you
                //                                                 so it is unique
                mItemsDatabase.push().setValue(item);

                // Clear input box
               item_EditText.setText("");
               quantity_EditText.setText("");
            }
        });



        //create ChildEventListener for listening get/read from items Firebase REALTTIME database
        items_childEventListener = new ChildEventListener() {

            //method called whenever a new item added into the items JSON list of database
            //  AND when this listener is first attached it will automatically call for every
            //    item already existing in the database
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //dataSnapshot contains the item added that triggered this listener code
                Item newItem = dataSnapshot.getValue(Item.class);  //list deserializes the JSON string into an Item object

                //now add this new item to the list adapter for items AND it will get displayed
                itemsAdapter.add(newItem);

            }


            //method called when an item is changed
            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            }

            //method called when item is deleted
            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
            }

            //method called when item's location/order in the list of items in JSON items list in database
            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }

            //method called when some kind of error occurred
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        };

        //register the ChildEventListener for items created above for our mItemsDatabase
        //  which points to the items JSON list of our Firebase database
        mItemsDatabase.addChildEventListener(items_childEventListener);
    }
}
