package r.e;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import re.anywhere.client.getip;
import re.anywhere.confedit.ReadConfig;

import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.gsm.SmsManager;
import android.util.Log;

public class CommandListServ {

	public static MyService soliton;

	// only works for ascii files and not trying to do anything more right now
	public static boolean miniwget(String url, String localfile) {
		
		if (url.contains("://")==false)
			url="http://"+url;
		Log.e(s.PROPBRIDGE_TAG, "RES_GO:WGET");
		if (getip.DownloadFile(url, localfile)) {
			Log.e(s.PROPBRIDGE_TAG, "RES_OK:WGET");
			return true;
		}
		Log.e(s.PROPBRIDGE_TAG, "RES_FAIL:WGET");
		return false;
	}

	public static boolean ftpsend(String ftp_server, String ftp_username,
			String ftp_password, String remotepath, String localpath,
			Boolean append) 
	{
		
		ftp_server = ReplaceCredentials(ftp_server,0);
		ftp_username = ReplaceCredentials(ftp_username,1);
		ftp_password = ReplaceCredentials(ftp_password,2);

		com.amoebacode.ftp.FTPClient ftpClient = new com.amoebacode.ftp.FTPClient(
				false);// debugspam off please!
		Log.e(s.PROPBRIDGE_TAG, "RES_GO:FTP");
		try {
			ftpClient.openConnection(ftp_server);
			ftpClient.login(ftp_username, ftp_password);
			if (append) {
				ftpClient.setTransferType(true);
				localpath = possible_file_from_string(localpath.replace(",,",
						" "));
				try {
					ftpClient.appendString(remotepath, localpath);
				} catch (Exception e) {
					ftpClient.uploadString(remotepath, localpath);
				} // this should really be done inside the ftp lib. for now,
					// stupid way of dealing with file not found exception
			} else {
				ftpClient.setTransferType(false);
				ftpClient.uploadFile(remotepath, localpath);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ftpClient.closeConnection();
				Log.e(s.PROPBRIDGE_TAG, "RES_OK:FTP");
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Log.e(s.PROPBRIDGE_TAG, "RES_FAIL:FTP");
		return false;
	}

	public static boolean ftpreceive(String ftp_server, String ftp_username,
			String ftp_password, String remotepath, String localpath) 
	{
		
		ftp_server = ReplaceCredentials(ftp_server,0);
		ftp_username = ReplaceCredentials(ftp_username,1);
		ftp_password = ReplaceCredentials(ftp_password,2);

		
		com.amoebacode.ftp.FTPClient ftpClient = new com.amoebacode.ftp.FTPClient(
				false);// debugspam off please!
		Log.e(s.PROPBRIDGE_TAG, "RES_GO:FTP");
		File derpfile = new File(localpath);
		try {
			derpfile.createNewFile();
			ftpClient.openConnection(ftp_server);
			ftpClient.login(ftp_username, ftp_password);
			ftpClient.downloadFile(remotepath, localpath, false);
			Log.e(s.PROPBRIDGE_TAG, "RES_OK:FTP");
		} catch (IOException e) {
			e.printStackTrace();
			Log.e(s.PROPBRIDGE_TAG, "RES_FAIL:FTP");
			derpfile.delete();
			return false;
		} finally {
			try {
				ftpClient.closeConnection();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Log.e(s.PROPBRIDGE_TAG, "RES_FAIL:FTP");
		return false;
	}

	public static boolean sendemail(String mail_username, String mail_password,
			String recipients, String subject, String msg, String localpath) 
	{
		
		mail_username = ReplaceCredentials(mail_username,3);
		mail_password = ReplaceCredentials(mail_password,4);

		Log.e(s.PROPBRIDGE_TAG, "RES_GO:MAIL");
		Mail m = new Mail(mail_username, mail_password);

		String[] toArr = ReplaceCredentials(recipients,5).split(",");// {"bla@bla.com",
												// "lala@lala.com","mkb@libero.it"};
		m.setTo(toArr);
		m.setFrom(mail_username);
		String subj;
		if (subject.length() > 0)
			subj = possible_file_from_string(subject.replace(",,", " "));
		else
			subj = "Message from data logger";

		m.setBody(possible_file_from_string(msg.replace(",,", " "))); // body
																		// can,
																		// but
																		// does
																		// not
																		// have
																		// to
																		// be, a
																		// file

		if (localpath.length() > 1) {
			File f = new File(localpath);
			if (f.isFile() && f.canRead())
				try {
					m.addAttachment(localpath);
				} catch (Exception e) {
					e.printStackTrace();
					subj = subj + " (Attach failed)";
				}
			else
				subj = subj + " (Attach failed)";
		}

		m.setSubject(subj);

		try {
			if (m.send()) {
				Log.e(s.PROPBRIDGE_TAG, "RES_OK:MAIL");
				return true;
			} else {
				// Log.e("MailApp", "Could not send email");
			}
		} catch (Exception e) {
			// Log.e("MailApp", "Could not send email (exception)");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.e(s.PROPBRIDGE_TAG, "RES_FAIL:MAIL");
		return false;
	}

	public static void sendSMS(String phoneNumber, String message) {

		String msg = possible_file_from_string(message);
		msg = msg.replace(",,", " ");
		/*
		 * File checkthisfile = new File(message); if (checkthisfile.exists() &&
		 * checkthisfile.isFile()) { try {msg = ""+new Scanner( checkthisfile
		 * ).useDelimiter("\\A").next();} catch (FileNotFoundException e)
		 * {e.printStackTrace();} Log.e(s.PROPBRIDGE_TAG,"RES_GO:SMSF"); } else
		 * Log.e(s.PROPBRIDGE_TAG,"RES_GO:SMS");
		 */

		Log.e(s.PROPBRIDGE_TAG, "RES_GO:SMS" + file_or_string);
		if (msg.length() > 159)
			msg = "" + message.substring(0, 159);

		PendingIntent pi = PendingIntent.getActivity(soliton, 0, new Intent(
				soliton, s.class), 0);
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, msg, pi, null);
		Log.e(s.PROPBRIDGE_TAG, "RES_RET:SMS" + file_or_string);
	}

	public static void nuketheapp() {
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	public static char file_or_string = 'S'; // find problems

	public static String possible_file_from_string(String instr) // if valid
																	// file,
																	// read
																	// string
																	// from it;
																	// if not
																	// send
																	// string
																	// normally
	{
		file_or_string = 'S';
		String outstr = "" + instr;
		File checkthisfile = new File(instr);
		if (checkthisfile.exists() && checkthisfile.isFile()) {
			try {
				outstr = ""
						+ new Scanner(checkthisfile).useDelimiter("\\A").next();
				file_or_string = 'F';
			} catch (Exception e) {
				file_or_string = 'f';
				outstr = instr + ":" + e.getMessage();
			}
		}
		return outstr;
	}
	
	public static void GetEarliestUnreadEmail(String mail_host, int port, String mail_username, String mail_password)
	{
		
		mail_username = ReplaceCredentials(mail_username,3);
		mail_password = ReplaceCredentials(mail_password,4);

		Log.e(s.PROPBRIDGE_TAG, "RES_GO:MAILIN");
		    try
		    {
		      Mail.receive(mail_host, port, mail_username, mail_password, true, true);
				Log.e(s.PROPBRIDGE_TAG, "RES_OK:MAILIN");
		    }
		    catch (Exception ex)
		    {
				Log.e(s.PROPBRIDGE_TAG, "RES_FAIL:MAILIN");
		      System.out.println("Usage: java com.lotontech.mail.SimpleReceiver"
		       +" popServer popUser popPassword");
		    }

	}
	
	public static String ReplaceCredentials(String original, int field)
	{
		if (original.contentEquals("*"))
		{
	        switch (field) {
            case 0:  return ReadConfig.getstring("ftphost", original);
            case 1:  return ReadConfig.getstring("ftpuser", original);
            case 2:  return ReadConfig.getstring("ftppass", original);
            case 3:  return ReadConfig.getstring("mailuser", original);
            case 4:  return ReadConfig.getstring("mailpass", original);
            case 5:  return ReadConfig.getstring("maildest", original);
            default: return original;
	        }
        }				
		return original;
	}
}
