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 com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

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;
    @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 button
        mStoreButton = (Button) findViewById(R.id.buttonStore);

        //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("");
            }
        });
    }
}
