package hh.dejsem.fm;

import android.content.Context;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import hh.dejsem.R;
import hh.lib.D;

/**
 * ----------------------------------------------------------
 * holds and updates view on progress of one file transfer task
 * ----------------------------------------------------------
 */
public class TaskProgress {
	D d;
	public EntitySize es;
	long updTs;
	int pct = 0;
	String fn;
	LinearLayout listRow;
	TextView progressFiles, progressFn, progressNum;
	ProgressBar progressBar;
	ImageView cancelButton;

	TaskProgress(D d) { this(d, new EntitySize().zero()); }

	TaskProgress(D d, EntitySize target) {
		this.d = d.klon(this);
		/*es = new EntitySize(target);*/
		es = target;
		final LayoutInflater lInflater = LayoutInflater.from(d.getContext());
		listRow = (LinearLayout)lInflater.inflate(R.layout.progress_entry, null);
		progressFiles = ((TextView)(listRow.findViewById(R.id.progressFiles)));
		progressFn = ((TextView)(listRow.findViewById(R.id.progressFn)));
		progressNum = ((TextView)(listRow.findViewById(R.id.progressNum)));
		progressBar = ((ProgressBar)(listRow.findViewById(R.id.progressBar)));
		cancelButton = ((ImageView)(listRow.findViewById(R.id.cancel)));
	}

	void updateView(NetTaskRef netTaskRef, View.OnClickListener cancelListener) {
		Bundle b = es.getTarget();
		int i = b.getInt(EntitySize.TARGET_FNUM_KEY);
		String files = String.format(" %d file%s", i, (i > 1 ? "s" : ""));
		i = b.getInt(EntitySize.TARGET_DNUM_KEY);
		if(i > 0) files += String.format(" in %d dir%s", i, (i > 1 ? "s" : ""));
		files += ": ";
		b = es.getStatus();
		final Context c = d.getContext();
		pct = b.getInt(EntitySize.PCT_KEY);
		String formatted = String.format("%s of %s (%d%%) %s",
				Formatter.formatFileSize(c, b.getLong(EntitySize.RUNNING_SIZE_KEY)),
				Formatter.formatFileSize(c, b.getLong(EntitySize.TARGET_SIZE_KEY)),
				pct,
				(b.getBoolean(EntitySize.STALLED_KEY) ? " stalled" : ""));
		fn = b.getString(EntitySize.FN_KEY);

		progressFiles.setText(files);
		progressFn.setText(fn);
		progressNum.setText(formatted);
		progressBar.setProgress(pct);
		cancelButton.setTag(netTaskRef);
		cancelButton.setOnClickListener(cancelListener);
		updTs = System.currentTimeMillis();
	}
}

