package hh.dejsem;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.telephony.SmsManager;

import java.util.List;

import hh.dejsem.fm.TransferAlert;
import hh.lib.D;

/**
 * share http URL
 * ● complete URL from URI path
 * ● copy URL to clipboard
 * ● optionally share URL
 */
public class SendUriNG implements DialogInterface.OnClickListener {

	public static void decideSendUri(String uriPath) {
		if(uriPath != null && uriPath.length() > 0)
			K.app.startActivity(new Intent(K.app, TransferAlert.class)
					.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)     /*Intent.FLAG_ACTIVITY_SINGLE_TOP)*/
					.putExtra(K.ACTION_KEY, K.TRANSFER_SEND_URI)
					.putExtra(K.TXT_KEY, uriPath)
			);
	}

	D d;
	Context c;
	AlertDialog alert;
	public String uriStr;

	public SendUriNG(D d, Context c, String uriPath) {
		this.d = d.klon(this);
		this.c = c;
		uriStr = buildUri(uriPath).toString();
		if(this.d.ll(4)) this.d.l("exposed as " + uriStr);
		((ClipboardManager)(c.getSystemService(Context.CLIPBOARD_SERVICE)))     // pin URL on clipboard
				.setPrimaryClip(ClipData.newPlainText("exposed URL", uriStr));
	}

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

	Uri buildUri(String uriPath) {
		return new Uri.Builder().scheme("http").authority(Prefs.host).path(uriPath).build();
	}

	void send() {
		Intent actionSEND = new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, uriStr).setTypeAndNormalize("text/plain");
		c.startActivity(Intent.createChooser(actionSEND, null));
	}

	public void sendTestSMS(String url) {
		if(d.ll(4)) d.l("sent by SMS: " + url);
		SmsManager sms = SmsManager.getDefault();
		List<String> messages = sms.divideMessage(url);
		/*String recipient = recipientTextEdit.getText().toString();*/
		/*String recipient = "601593811";*/
		String recipient = "607677931";
		for (String message : messages) {
			if(d.ll(5)) d.l(String.format("sms.sendTextMessage(\"%s\", null, \"%s\", null, null)", recipient, message));
			sms.sendTextMessage(recipient, null, message, null, null);
		}
	}
}
