package com.example.mortezasaadat.app65;

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.TextView;

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;

public class MainActivity extends AppCompatActivity {


    EditText edtBoxerName, edtPunchPower, edtPunchSpeed;

    Button btnSendDataToServer;

    TextView txtReceivedData;

    FirebaseDatabase database;
    DatabaseReference databaseReference;

    private String oldTxtReceivedData;


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


        edtBoxerName = (EditText) findViewById(R.id.edtBoxerName);
       edtPunchPower = (EditText) findViewById(R.id.edtBoxerPunchPower);
        edtPunchSpeed = (EditText) findViewById(R.id.edtBoxerPunchSpeed);
        btnSendDataToServer = (Button) findViewById(R.id.btnSendData);
        txtReceivedData = (TextView) findViewById(R.id.txtReceivedData);



        database = FirebaseDatabase.getInstance();
        databaseReference = database.getReference();


        btnSendDataToServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Boxer boxer = new Boxer(edtBoxerName.getText().toString(),
                       Integer.parseInt(edtPunchPower.getText().toString()),
                       Integer.parseInt(edtPunchSpeed.getText().toString()));
                databaseReference.child(databaseReference.push().getKey()).setValue(boxer);


            }
        });



        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                oldTxtReceivedData = "";

                for (DataSnapshot child : dataSnapshot.getChildren()) {

                    Boxer boxer = child.getValue(Boxer.class);
                    if (oldTxtReceivedData == null) {
                        oldTxtReceivedData = " ";
                    }
                    txtReceivedData.setText(oldTxtReceivedData + boxer.getBoxerName() + " - " +
                            boxer.getPunchPower() + " - " +
                            boxer.getPunchSpeed() + "\n");
                    oldTxtReceivedData = txtReceivedData.getText().toString();

                }



            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


    }
}
