package hh.dejsem.fm;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;

import hh.dejsem.Act;
import hh.dejsem.K;
import hh.dejsem.Main;
import hh.dejsem.SendUriNG;

/**
 * Activita k zobrazení zpráv z LongAsyncTask, který obecně nemá dostupné hlavní UI
 */
public class TransferAlert
		extends Act
		implements
			DialogInterface.OnClickListener,
			DialogInterface.OnDismissListener,
			DialogInterface.OnKeyListener {

	AlertDialog.Builder alertBuilder;
	AlertDialog alert;

	@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);
		Main.eyeCatcher(d, this);
		d.logPrefix += "[" + getIntent().getIntExtra("IDX", 0) + "]";
		alertBuilder = new AlertDialog.Builder(this).setOnKeyListener(this);
		action(getIntent().getIntExtra(K.ACTION_KEY, 0));
	}

	@Override
	public void onResume() {
		super.onResume();
		if(alert != null) alert.show();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(alert != null) alert.dismiss();
	}

	@Override
	public void onDismiss(DialogInterface d) { finish(); }

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

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

	void action(int action) {
		if(d.ll(4)) d.l("action=" + action);
		switch(action) {
			case K.TRANSFER_WARNING:
				displayMsg("WARNING");
				break;
			case K.TRANSFER_ABEND:
				displayMsg("ABEND");
				break;
			case K.TRANSFER_DISPLAY_TEST:
				displayMsg("ALERT TEST");
				break;
			case K.TRANSFER_SEND_URI:
				decideUriMsg();
				break;
		}
	}

	void displayMsg(String title) {
		alert = alertBuilder
				.setTitle(String.format("%s %s", getPackageName(), title))
				.setMessage(getIntent().getStringExtra(K.TXT_KEY))
				.setPositiveButton("OK", this)
				.create();
		alert.setCanceledOnTouchOutside(false);
	}

	void decideUriMsg() {
		SendUriNG sendUri = new SendUriNG(d, this, getIntent().getStringExtra(K.TXT_KEY));
		alert = alertBuilder
				.setTitle(String.format("%s: %s", getPackageName(), "expose to HTTP is complete"))
				.setMessage(String.format("URL %s is now on clipboard. Should it be sent?", sendUri.uriStr))
				.setPositiveButton("YES", sendUri)
				.setNegativeButton("NO", this)
				.create();
		alert.setCanceledOnTouchOutside(false);
	}

	void terminate() {
		d.l(4,"terminate");
		alert.dismiss();
		alert = null;
		finish();
	}
}
