package hh.dejsem.fm;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.Stack;

import hh.dejsem.Act;
import hh.dejsem.K;
import hh.dejsem.Main;
import hh.lib.D;

/**
 * Aktivita sloužící k zobrazení detailů o průběhu déle travajících datových přenosů
 * <p>
 * ● aktivita se spouští z notifikace v Notification Bar
 * <p>
 * ● informace se zobrazují AlertDialogem jako list of progress bars
 * <p>
 * ● klik na cancel icon příslušný přenos bezpodmínečně ukončí
 */
public class ProgressMonitor
		extends Act
		implements
			Runnable,
			DialogInterface.OnClickListener,
			DialogInterface.OnDismissListener,
			DialogInterface.OnKeyListener,
			View.OnClickListener {

	Handler handler = new Handler();
	ProgressListAdapter listAdapter = null;
    final String fragmentTitle = "DEJSEM TRANSFER MONITOR";
	Stack stack = new Stack();

	@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);
		Main.eyeCatcher(d, this);
		action(getIntent().getIntExtra(K.ACTION_KEY, 0));
	}

	@Override
	public void onResume() {
		super.onResume();
		if(transferInProgress()) handler.postDelayed(this, K.transfProgress.refreshInterval);
	}

	@Override
	public void onPause() {
		super.onPause();
		handler.removeCallbacks(this);
	}

	@Override
	public void onDestroy() { 
		super.onDestroy();
		while(!stack.empty()) ((AlertDialog)stack.pop()).dismiss();
	}

	@Override
	public void run() {
		if(K.transfProgress.transfCnt() == 0) {
			terminate();
			return;
		}
		listAdapter.notifyDataSetChanged();
		handler.postDelayed(this, K.transfProgress.refreshInterval);
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		d.l("+++ onDismiss()");
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(d.ll(4)) d.l("onKeyDown, keyCode=" + keyCode);
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			terminate();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
		if(d.ll(4)) d.l("onKey, keyCode=" + keyCode);
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			if(event.getAction() == KeyEvent.ACTION_UP) terminate();
			return true;
		}
		return false;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if(d.ll(4)) d.l("DialogInterface.onClick()");
		terminate();
	}

	@Override
	public void onClick(View v) {   // click na cancel button v transfer listu
		NetTaskRef netTaskRef = (NetTaskRef) v.getTag();
		if(d.ll(4)) d.l("View.onClick(), cancel button, netTaskRef=" + netTaskRef);
		netTaskRef.go = false;
		if(K.transfProgress.transfCnt() == 1) terminate();     // poslední task, zhasnout transfer list
	}

	void action(int action) {
		if(d.ll(4)) d.l("action=" + action);
		if(action == K.TRANSFER_PIN_NOTIFICATION) {
			if(transferInProgress()) {
				d.l(4,"pin up transfer notification");
				K.transfProgress.barNotif.pin();
			}
		}
		else if(action == K.TRANSFER_DISPLAY_LIST) {
			if(transferInProgress()) {
				d.l(4,"transfer monitor activation...");
				// getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
				K.transfProgress.barNotif.pin();
				if(listAdapter == null) listAdapter = new ProgressListAdapter(d, this);

				AlertDialog progressList = new AlertDialog.Builder(this)
						.setAdapter(listAdapter,this)
						.setTitle(fragmentTitle)
						.setOnKeyListener(this)
						.create();
				progressList.setCanceledOnTouchOutside(false);
				progressList.show();
				stack.push(progressList);

				handler.postDelayed(this, K.transfProgress.refreshInterval);
				d.l(4, "transfer monitor activated");
			}
			else terminate();
		}
	}

	void terminate() {
		if(!stack.empty()) ((AlertDialog)stack.pop()).dismiss();
		if(stack.empty()) finish();
	}

	boolean transferInProgress() {
		if(K.transfProgress != null) return K.transfProgress.transfCnt() > 0;
		else return false;
	}

	/**----------------------------------------------------------
	 * progress list adapter
	 * ----------------------------------------------------------*/
	class ProgressListAdapter extends BaseAdapter {

		D d;
		View.OnClickListener cancelListener;

		ProgressListAdapter(D d, View.OnClickListener cancelListener) {
			this.d = d.klon(this);
			this.cancelListener = cancelListener;
			}

		public int getCount() { return K.transfProgress == null ? 0 : K.transfProgress.transfCnt(); }

		public Object getItem(int position) { return null; }

		public long getItemId(int position) { return position; }

		public int getViewTypeCount() { return 8; }

		public View getView(int position, View listEntry, ViewGroup parent) {
			if(d.ll(5)) d.l(String.format("getView, position=%d, view=%x", position, listEntry == null ? 0 : listEntry.hashCode()));
			synchronized(K.transfProgress.statSet) {
				if(position < K.transfProgress.statSet.size()) {
					final NetTaskRef netTaskRef = K.transfProgress.statSet.get(position);
					final TaskProgress taskProgress = netTaskRef.getProgress();
					taskProgress.updateView(netTaskRef, cancelListener);
					if(d.ll(5)) d.l(String.format("getView return, position=%d, view=%x", position, taskProgress.listRow.hashCode()));
					return taskProgress.listRow;
				}
				else return null;
			}
		}
	}
}
