package hh.dejsem.lastmile;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import hh.dejsem.K;
import hh.dejsem.R;
import hh.dejsem.net.NetNode;
import hh.lib.D;
import hh.lib.DF;

/**
 * last mile throughput meter Activity
 */
public class LastMileMeterFrag extends DF implements View.OnClickListener {

	final static String TITLETEXT = "last mile";

	public static LastMileMeterFrag instantiate(D d) {
		LastMileMeterFrag lf = new LastMileMeterFrag();
		lf.d = d.klon(lf);
		return lf;
	}

	LastMileMeterRun netTask = null;

	@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		View lastMile = inflater.inflate(R.layout.last_mile, null);
		lastMile.findViewById(R.id.intrr).setOnClickListener(this);
		d.tv = (TextView)lastMile.findViewById(R.id.tv);
		d.sc = (ScrollView)lastMile.findViewById(R.id.sc);
		return lastMile;
	}

	@Override
	public void onResume() {
		super.onResume();
		K.title.setText(TITLETEXT).update();
		try {
			if (K.netNode == null) K.netNode = new NetNode(d);
			run();
		}
		catch(Exception e) { d.abendMsg(e); }
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(netTask != null) netTask.cancel(false);
	}

	@Override
	public void onClick(View v) {
		if(netTask != null) {
			if (netTask.inProgress) {
				netTask.cancel(false);
				netTask.inProgress = false;
			} else run();
		}
	}

	void run() {
		if(netTask == null || !netTask.inProgress) {
			netTask = new LastMileMeterRun(d);
			netTask.execute();
		}
	}
}
