package com.momrach.basichandler;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    WorkerTrhead mWorkerThread;
    Button btnButton, btnHello;
    TextView tvText;

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

        btnButton = (Button)  findViewById(R.id.btnButton);
        btnButton.setOnClickListener(this);
        btnHello = (Button)  findViewById(R.id.btnHello);
        btnHello.setOnClickListener(this);
        tvText = (TextView) findViewById(R.id.tvText);
        tvText.setText("Not running yet");

        mWorkerThread = new WorkerTrhead(this); //Creamos el Thread.
        mWorkerThread.start();  //Lanzamos el Thread. Es un Looper Thread. Tiene un Looper propio y no para
    }

    @Override
    protected void onDestroy() {
        mWorkerThread.mHandler.getLooper().quit();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        TextView tvText;
        switch (v.getId()){
            case R.id.btnButton:
                tvText = findViewById(R.id.tvText);
                if (tvText.getText() != "Running") {
                    if (mWorkerThread.mHandler != null) {
                        tvText.setText("Running");
                        Message msg = mWorkerThread.mHandler.obtainMessage(0);
                        mWorkerThread.mHandler.sendMessage(msg);
                    }
                }
                break;
            case R.id.btnHello:
                Toast.makeText(MainActivity.this,"Hola amigos", Toast.LENGTH_LONG).show();
        }
    }
}
