package com.momrach.basichandlerthread;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;

import java.lang.ref.WeakReference;


public class WorkerThread extends HandlerThread {
    private Handler mHandler;
    private Handler mUIHandler;
    private WeakReference<Activity>  theActivity;
    int mDelay = 10000; //10 seconds
    static int counter;
    private boolean handlerSetted;


    public WorkerThread(Context theActivity, String name) {
        super(name);
        this.theActivity = new WeakReference<>((Activity)theActivity);
        this.mUIHandler = new Handler(Looper.getMainLooper());
        this.handlerSetted  = false;
    }

    public void SendMessage(int what){
        //NO podemos inicializar el handler hasta que el thread no esté creado, por eso no va esto en el construtor.
        if (!handlerSetted){
            mHandler = new MyHandler(getLooper()); //El thread ya esta creado con looper, que pasamos al constructor.
            handlerSetted = true;
        }
        //Obtenemos el mensaje primero del Handler
        Message msg = mHandler.obtainMessage(what);
        mHandler.sendMessage(msg);
    }

    public void PostTask(Runnable runnable){
        //NO podemos inicializar el handler hasta que el thread no esté creado, por eso no va esto en el construtor.
        if (!handlerSetted){
            mHandler = new MyHandler(getLooper()); //El thread ya esta creado con looper, que pasamos al constructor.
            handlerSetted = true;
        }
        mHandler.post(runnable);
    }

    public void Quit(){
        getLooper().quit();
    }

    public Looper GetLooper(){
        return mHandler.getLooper();
    }

    private class MyHandler extends Handler
    {
        public MyHandler(Looper looper) {

            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            if (theActivity.get() != null){
                if (msg.what == 0) {
                    counter++;
                    doLongRunningOperation();
                    mUIHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            TextView tvText;
                            tvText = (TextView) theActivity.get().findViewById(R.id.tvText);
                            tvText.setText("Run " + counter + " times.");
                        }
                    });
                }
            }
            else{
                mUIHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        TextView tvText;
                        tvText = (TextView) theActivity.get().findViewById(R.id.tvText);
                        tvText.setText("The message was lost, try again, please.");
                    }
                });
            }

        }
    }

    private void doLongRunningOperation(){
        //Sleeps total i x mDelay = x minute.
        for (int i=0; i<1; i++) {
            sleep();
        }
    }

    private void sleep() {
        try {
            Thread.sleep(mDelay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
