
package net.indivia.hacklabbo.statusreader;

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.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

@SuppressLint("NewApi")
public class CheckUpdate extends Service {
  /*private final static String app_site = "http://isopen.hacklabbo.indivia.net/";*/
  private final static String LOG_TAG = "CheckUpdate";
  private final static String app_apk = "net.indivia.hacklabbo.statusreader";
  private final static String app_site = "http://ginex.indivia.net/";
  private final static String app_www_current_apk = "latest.apk";
  private final static String app_www_current_version = "update.json";
  //DEBUG:
  private final static String app_www_current_version_fail = "update-fail.json";
  private final static String app_www_current_version_true = "update-true.json";

  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;

  @Override
  public void onCreate() {
    super.onCreate();
    res = getResources();

    bgThread = new BgThread();
    bgThread.start();
    
    
    Intent intent = new Intent(this, Downloader.class);
    String app_uri = app_site + app_www_current_apk;
    intent.putExtra("checkUpdate", NOTIFY_APP_UPDATE);
    intent.setData(Uri.parse(app_uri));
    intent.putExtra("urlpath", app_uri);
    
    pIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT );
    
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    	notifyBuilder();
    else
    	getNotify();
    
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    Log.i(LOG_TAG, "Service Created");
  }
  
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public void notifyBuilder(){
	    notification = new Notification.Builder(this)
	    	.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
        	.setContentTitle(getString(R.string.app_update_notify_title))
        	.setContentText(getString(R.string.app_update_new_version))
        	.setLights(0xFFFF0000, 500, 500)
        	.setSmallIcon(R.drawable.software)
        	.setContentIntent(pIntent)
        	.build();
  }
  
  @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() {
      try {
    	  //String json = SNetwork.GET(app_site + app_www_current_version);
    	  String json = SNetwork.GET(app_site + app_www_current_version_true);
    	  JSONObject jObject = new JSONObject(json);
    	  
    	  int newVersion = jObject.getInt("version");
    	  int curVersion = getPackageManager().getPackageInfo(app_apk, 0).versionCode;
    	  //Log.d(LOG_TAG,"cur:"+curVersion+" new:"+newVersion);

    	  if (newVersion > curVersion){
    		  if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    			  notificationManager.notify(0, notification);
    		  else
    			  sendNotification(newVersion);
    	  }
 
      } catch (Exception e) {
    	  e.printStackTrace();
      }

      stopSelf();
    }
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    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;
  }
}
