package com.momrach.basichandlerthreadmessages;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    WorkerThread mWorkerThread;
    Handler uiHandler;
    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");

        //Creamos el uiHandler, aquí puesto que correrá las tareas en el UIThread. Parece más lógico.
        uiHandler = new UIHandler();

        mWorkerThread = new WorkerThread(uiHandler, "My Worker Thread"); //Creamos el Thread.
        mWorkerThread.start();  //Lanzamos el Thread. Es un Looper Thread. Tiene un Looper propio y no para

    }

    @Override
    protected void onDestroy() {
        mWorkerThread.Quit();
        super.onDestroy();
    }

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

    private class UIHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Globals.WT_DONE:
                    int counter = msg.arg1;
                    tvText.setText("Run " + counter + " times.");
                    break;
                case Globals.WT_RUNNING:
                    tvText.setText("The task is currently running, please be patient.");
                    break;
            }
        }
    }
}
