package com.example.miguel.saludoforresulticon;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import saludoforresulticon.R;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button btnSaludo, btnSalir;
    Switch swForResult;
    EditText etText;

    static final int FOR_RESULT_REQUEST = 1; // The request code

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

        btnSaludo = (Button) findViewById(R.id.btnSaludo);
        btnSalir=(Button)findViewById(R.id.btnSalir);
        swForResult=(Switch) findViewById(R.id.swForResult);
        etText = (EditText) findViewById(R.id.edtSaludo);

        btnSaludo.setOnClickListener(this);
        btnSalir.setOnClickListener(this);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setIcon(R.mipmap.ic_tiger);
        actionBar.setDisplayShowHomeEnabled(true);

        // Activar flecha ir atrás (ir a la Parent Activity declarada en el manifest)
        //actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnSaludo: //Boton Saludo, envía datos a la activiti Saludo
                String strSaludo = etText.getText().toString();
                Boolean forResult = swForResult.isChecked();

                if (!(strSaludo.isEmpty())) {
                    Intent intent = new Intent(this, Saludo.class);
                    intent.putExtra("txtSaludo", strSaludo);

                    if (forResult) {
                        startActivityForResult(intent,FOR_RESULT_REQUEST);
                    }
                    else {
                        startActivity(intent);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Rellena el campo de texto", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnSalir: //Boton Salir, Termina la aplicación
                finish();
                break;
            default:
                break;
            }
    } //onClick


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == FOR_RESULT_REQUEST) {
            if(resultCode == Activity.RESULT_OK){

                etText.setText(data.getStringExtra("txtResult"));
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                //Write your code if there's no result
            }
        }
    }//onActivityResult
}
