package net.indivia.hacklabbo.statusreader;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

@SuppressLint("NewApi")
public class StatusUpdate extends Service {
	// private final static String app_site =
	// "http://isopen.hacklabbo.indivia.net/";
	private final static String app_site = "http://ginex.indivia.net/";
	private final static String LOG_TAG = "StatusUpdate";
	// public final static String DEF_SITE =
	// "http://isopen.hacklabbo.indivia.net/hacklabbo/state.json";
	public final static String DEF_SITE = "http://ginex.indivia.net/state.json";
	private final static String app_www_current_apk = "latest.apk";

	public final static int NOTIFY_APP_UPDATE = 2;

	private BgThread bgThread;
	private NotificationManager notificationManager;
	private Notification notification;
	private PendingIntent pIntent;
	private int notificationNumber;
	private Resources res;
	private static String serverName;
	private static Boolean oldStatus, isCicleService;
	private static int refreshTime;
	private ConnectivityManager cm; 
	@Override
	public void onCreate() {
		super.onCreate();
		res = getResources();
		cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		bgThread = new BgThread();
		bgThread.start();

		String app_uri = app_site + app_www_current_apk;
		Intent i = new Intent(this, MainActivity.class);
		i.putExtra("checkUpdate", NOTIFY_APP_UPDATE);
		i.setData(Uri.parse(app_uri));
		i.putExtra("urlpath", app_uri);

		pIntent = PendingIntent.getActivity(this, 0, i,
				PendingIntent.FLAG_UPDATE_CURRENT);

		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		Log.i(LOG_TAG, "Service Created");
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void notifyBuilder(String status) {
		notification = new Notification.Builder(this)
				.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
				// .setContentTitle(getString(R.string.app_update_notify_title))
				.setContentTitle("StatusReader: cambio di stato")
				.setContentText("Stato cambiato a: " + status)
				.setLights(0xFFFF0000, 500, 500)
				// TODO: cambiare l'icona
				.setSmallIcon(R.drawable.software).setContentIntent(pIntent)
				.setAutoCancel(true).build();
	}

	// TODO: cambiare titolo icone
	@SuppressWarnings("deprecation")
	public void getNotify() {
		notification = new Notification(R.drawable.software,
				getString(R.string.app_update_notify_title),
				System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

	}

	@SuppressWarnings("deprecation")
	public void sendNotification(int newVersion) {
		notification.number = ++notificationNumber;
		notification.setLatestEventInfo(this,
				res.getString(R.string.app_update_notify_title),
				res.getString(R.string.app_update_new_version), pIntent);

		notificationManager.notify(NOTIFY_APP_UPDATE, notification);
	}

	private final class BgThread extends Thread {
		public void run() {
			do {
				if (SNetwork.isConnected(cm)) {
					Log.i(LOG_TAG, "Service Cicle");
					String json = SNetwork.GET(serverName);
					try {
						JSONObject jObject = new JSONObject(json);
						boolean newStatus = jObject.getBoolean("open");
						String statusChange = jObject.getString("date");

						Calendar c = Calendar.getInstance();
						SimpleDateFormat dateFormat = new SimpleDateFormat(
								"yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.ITALY);
						String last_refresh = dateFormat.format(c.getTime());

						if (newStatus != oldStatus) {
							String status = res.getString(R.string.close);
							if (newStatus)
								status = res.getString(R.string.open);

							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
								notifyBuilder(status);
								notificationManager.notify(0, notification);
							} else {
								getNotify();
								sendNotification(1);
							}
						}
						SUtility.saveState(getApplicationContext(), newStatus,
								last_refresh, statusChange);

						if (!isCicleService) {
							stopSelf();
							Log.i(LOG_TAG, "Service stop");
							// setDisplay(newStatus, last_refresh, statusChange);
						}

						try {
							Thread.sleep(refreshTime);
						} catch (InterruptedException ie) {
							Log.d(LOG_TAG,
									"Qualcosa è andato storto con il timer.\n"
											+ ie.toString());
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					Log.d(LOG_TAG, "Non c'è connessione");
				}
			} while (isCicleService);
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		isCicleService = intent.getBooleanExtra("isCicleService", false);
		if (isCicleService)
			refreshTime = intent.getIntExtra("refreshTime", 0);

		serverName = intent.getStringExtra("serverName");
		oldStatus = intent.getBooleanExtra("oldStatus", false);

		Log.i(LOG_TAG, "Service Started");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(LOG_TAG, "Service Destroyed");
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
