package no.freedommedia.featurebooster.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import no.freedommedia.featurebooster.cmd.AlarmInfo;
import no.freedommedia.featurebooster.cmd.CalendarInfo;
import no.freedommedia.featurebooster.cmd.ContactInfo;
import no.freedommedia.featurebooster.cmd.EmailInfo;
import no.freedommedia.featurebooster.cmd.GlobalProperties;
import no.freedommedia.featurebooster.cmd.MyAlertBox;
import no.freedommedia.featurebooster.cmd.PhoneInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Browser;
import android.provider.Contacts;
import android.provider.MediaStore;
import android.provider.Browser.BookmarkColumns;
import android.provider.Contacts.ContactMethods;
import android.provider.Contacts.Organizations;
import android.provider.Contacts.People;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.gsm.SmsManager;
import android.util.Log;

public class AndroidHelper
{
	public static int wallpaperSet(String wallfile,Context c)throws UserException
	 { 
		 File rFile;
		 if(wallfile!=null)
		 { 
		    rFile = new File(wallfile);
		    if (rFile.exists()) 
		      {
		    	//Log.i("wallpaper path",""+wallfile);
		 	   	Bitmap newwallpaper=BitmapFactory.decodeFile(wallfile);
	 	
		 	   	try {
		 	   	
		 	   			c.setWallpaper(newwallpaper);
		 	   			
		 	   		}
		 	   	catch(StreamCorruptedException e)
		 	   	{
		 	   		throw new UserException(UserException.KErrMMEtelScFileInvalidated,e.getMessage());
		 	   	}
		 	   	catch (IOException e)
		 	   		{
						
						e.printStackTrace();
						throw new UserException(UserException.KErrGeneral,e.getMessage());
		 	   		}
		 	   	
		      }
		    else
		    {
		    	throw new UserException(UserException.KErrMMEtelScFileNotFound,"file not found");	
		    }
     	
		    		//broadcastIntent(new Intent(Intent.ACTION_WALLPAPER_CHANGED));
     	return UserException.success;
		}
		
		else{
				throw new UserException(UserException.KErrMMEtelScFileNotFound,"file is not exist");	
			}
		 
		
	 }
	
	
	//for setting theme
	
	public static boolean themesetting(int uid,Context c)throws UserException
	{
		try
		{
			c.setTheme(uid);
					
		}
		catch(Exception e)
		{
	
			throw new UserException(UserException.KErrGeneral,e.getMessage());
			
		}
		
		return true;
		
	}
	

	//FOR SMS SENDING
	 
	public static boolean sendSMS(String phoneNumber, String message, Context c)throws UserException
	    {  
		try
		{
	        String SENT = "SMS_SENT";
	        String DELIVERED = "SMS_DELIVERED";
	 
	        PendingIntent sentPI = PendingIntent.getBroadcast(c, 0,new Intent(SENT), 0);
	        PendingIntent deliveredPI = PendingIntent.getBroadcast(c, 0,new Intent(DELIVERED), 0);
	 
	        SmsManager sms = SmsManager.getDefault();
	        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);      
	    
	    }
		catch(IllegalArgumentException e)
		{
			throw new UserException(UserException.KErrCdmaOtaInvalidParameter,e.getMessage());
		}
		
		catch(Exception e)
		 {
			
			e.printStackTrace();
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		 }
		return true;
	    }
	
	
	
	
	
//Application List
	
	
	public static  String[] getAppList(Context context) throws UserException
	{
		String name="",filename="",path="",stringary[];
		int uid;
		
		try
		{
			
			PackageManager pm = context.getPackageManager();
		
			List<ApplicationInfo> uidname = pm.getInstalledApplications(PackageManager.GET_GIDS);
			List<ApplicationInfo> file = pm.getInstalledApplications(PackageManager.INSTALL_SUCCEEDED);
	    	
			stringary = new String[file.size()];
			Log.i("applist AH","Total Applications = "+file.size());
			for(int i=0;i<file.size();i++)
			{
				uid = uidname.get(i).uid;
				name = uidname.get(i).packageName;
				filename= (String)pm.getApplicationLabel(file.get(i));
				
				stringary[i] = uid+"::"+name+"::"+filename;
				
				//path = path+uid+"::"+name+"::"+filename+",";
			}
			//path = path.substring(0, path.lastIndexOf(','));
			
		
		}
		catch(SecurityException e)
		{
			throw new UserException(UserException.KErrAccessDenied,e.getMessage());
			
		}
		
		catch(Exception e)
		{
		   
			throw new UserException(UserException.KErrGeneral,e.getMessage());
			
		}
		return stringary;
	}
	
	public static void killApplication(Context context) throws UserException
	{
		try
		{
//			To disable the SMSListener Enable the Following Lines
//			PackageManager manager =context.getPackageManager();
//    		ComponentName cName =new ComponentName(context,StartUpReceiver.class); 
//    		manager.setComponentEnabledSetting(cName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
			System.exit(0);
			
			
			
		} 
		catch(Exception e)
		{
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
	}
	
	
	//add contact
	
	
	public static boolean addContact(Context act,ContactInfo ci) throws  UserException
	{
		try
		{	
			ContentValues values = new ContentValues();
		
			String Name = ci.getFirstname() + "  "+ ci.getLastname();
			
			values.put(People.NAME, Name);
			values.put(People.STARRED, 0);
			Uri newPerson =act.getContentResolver().insert(People.CONTENT_URI, values);
			
			
			Uri mobileUri = Uri.withAppendedPath(newPerson,People.Phones.CONTENT_DIRECTORY);
			values.clear();
			values.put(People.Phones.TYPE,People.Phones.TYPE_MOBILE);
			values.put(People.Phones.NUMBER,ci.getMobile());
			Uri Mobile = act.getContentResolver().insert(mobileUri, values);
			
			Uri phneUri = Uri.withAppendedPath(newPerson,People.Phones.CONTENT_DIRECTORY);
			values.clear();
			values.put(People.Phones.TYPE,People.Phones.TYPE_HOME);
			values.put(People.Phones.NUMBER,ci.getPhone());
			Uri Phone = act.getContentResolver().insert(phneUri, values);
			
			Uri emailUri = Uri.withAppendedPath(newPerson,People.ContactMethods.CONTENT_DIRECTORY);
			values.clear();
			values.put(People.ContactMethods.KIND,Contacts.KIND_EMAIL);
			values.put(People.ContactMethods.TYPE,ContactMethods.TYPE_HOME);
			values.put(People.ContactMethods.DATA,ci.getEmail());
			Uri Email = act.getContentResolver().insert(emailUri, values);
			
			
			Uri addressUri = Uri.withAppendedPath(newPerson,People.ContactMethods.CONTENT_DIRECTORY);
			values.clear();
			values.put(People.ContactMethods.KIND,Contacts.KIND_POSTAL);
			values.put(People.ContactMethods.TYPE,ContactMethods.TYPE_HOME);
			values.put(People.ContactMethods.DATA,ci.getAddress());
			Uri Addr = act.getContentResolver().insert(addressUri,values);
			
			Uri orgUri = Uri.withAppendedPath(newPerson,Organizations.CONTENT_DIRECTORY);
			values.clear();
			values.put(Organizations.COMPANY,ci.getCompany());
			values.put(Organizations.TYPE,Organizations.TYPE_WORK);
			Uri Org = act.getContentResolver().insert(orgUri, values);

			Uri titleUri = Uri.withAppendedPath(newPerson,Organizations.CONTENT_DIRECTORY);
			values.clear();
			values.put(Organizations.TYPE,Organizations.TITLE);
			values.put(Organizations.TITLE, ci.getTitle());
			Uri Title = act.getContentResolver().insert(titleUri, values);
			

			
			String PostalAddress = ci.getCity() +","+ ci.getState_province() +","+ ci.getCountry() +","+ ci.getZipcode() +","+ ci.getPobox();
			
			
			Uri PostalUri = Uri.withAppendedPath(newPerson,People.ContactMethods.CONTENT_DIRECTORY);
			values.clear();
			values.put(People.ContactMethods.KIND,Contacts.KIND_POSTAL);
			values.put(People.ContactMethods.TYPE,ContactMethods.TYPE_OTHER);
			values.put(People.ContactMethods.DATA,PostalAddress);
			Uri Country = act.getContentResolver().insert(PostalUri,values);
			
			
			
			
			
	/*First Way To add Image		-
			<ImageView android:id="@+id/contact_image"
			    android:layout_width="wrap_content"
			    android:layout_height="wrap_content" />
			
@Override
public void bindView(View view, Context context, Cursor cursor) {
    ImageView imageView = (ImageView) view.findViewById(R.id.contact_image);
 
    int id = _cursor.getColumnIndex(People._ID);
    Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, _cursor.getLong(id));
 
    Bitmap bitmap = People.loadContactPhoto(_context, uri, R.drawable.icon, null);
 
    imageView.setImageBitmap(bitmap);
 
    super.bindView(view, context, cursor);
}
			*/
			
			
			/* Second Way To Add Image
			 
			values.put(Media.DISPLAY_NAME, "JPEG FORMAT");
			values.put(Media.DESCRIPTION, "Adding into Contatcts");
			values.put(Media.MIME_TYPE, "jpeg/png");
			values.put(Media.DATA,ci.getImage_file());
			Uri Imageuri = act.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
			
			OutputStream outStream = act.getContentResolver().openOutputStream(Imageuri);
			Bitmap mBitmap = BitmapFactory.decodeResource(act.getResources(),R.drawable.icon);
		    mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
		    outStream.close();*/
			
			
			
		    
		}//try
		
		catch(SQLException e)
		{
			throw new UserException(UserException.KErrFailedToAddRecord,e.getMessage());
		}
		catch(Exception e)
		{
			
			throw new UserException(UserException.KErrGeneral,e.getMessage());	
		}
		return true;
		
	}
	
	
	public static boolean addCalendar_Meeting(Context c,CalendarInfo cmi,AlarmInfo ai) throws  UserException
	{
		try
		{
		
			String[] projection = new String[] { "_id", "name" };
			Uri calendars = Uri.parse("content://calendar/calendars");
			String calId=null; 
			String calName=null;
			Cursor managedCursor = c.getContentResolver().query(calendars, projection,"selected=1", null, null);
			if (managedCursor.moveToFirst()) 
			{
				 int nameColumn = managedCursor.getColumnIndex("name"); 
				 int idColumn = managedCursor.getColumnIndex("_id");
				 do {
				    calName = managedCursor.getString(nameColumn);
				    calId = managedCursor.getString(idColumn);
				    Log.i("Meeting","In do-while loop calendarName:CalendarId:"+calName+":"+calId);
				 } while (managedCursor.moveToNext());
			}
			else
			{
				Log.i("CalMeeting","No Calendar Providers...");
			}
			
			Log.i("Meeting","After loop calendarName:CalendarId:"+calName+":"+calId);
			Uri eventsUri = Uri.parse("content://calendar/events");
			ContentValues event = new ContentValues();
						//alarm described as minutes before starttime - alarm_offset field
						/*	Calendar cal = Calendar.getInstance();

		        		Intent intent        = new Intent();
						PendingIntent sender = PendingIntent.getBroadcast(c, 1234567, intent, 0);
						AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
						am.set(AlarmManager.RTC_WAKEUP, Long.parseLong(cmi.getAlarm_offset()),sender);*/
			String startTime =cmi.getStarttime();
			DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
			Date date = (Date)formatter.parse(startTime);
			Long startdate = date.getTime();
			String endTime = cmi.getEndtime();
			Date date1 = (Date)formatter.parse(endTime);
			Long enddate = date1.getTime();
			String alarm = cmi.getAlarm();
	        String repeat_rule = ai.repeatAlarm(cmi);
//	        Log.i("Meeting","id: "+calId+"title:"+cmi.getSubject()+"eventLocation:"+cmi.getLocation()+"description"+cmi.getDescription()+"hasAlarm"+alarm);
//	        Log.i("Meeting","startTime: "+startTime+" endTime:"+endTime);
//	        Log.i("Meeting","startdate: "+startdate+" endDate:"+enddate);
//	        Log.i("Meeting","startdate: "+startdate+" endDate:"+enddate);
	       
			event.put("calendar_id",calId );
			event.put("title", cmi.getSubject());			//subject it is a string
			event.put("eventLocation", cmi.getLocation());		//event location is a string 
			event.put("description", cmi.getDescription());	//description it is a string
			event.put("dtstart", startdate);				//start time <string dd-mm-yyyy tt:mm:ss>
			event.put("dtend", enddate);					//end time <string dd-mm-yyyy tt:mm:ss>
			event.put("hasAlarm", alarm); // alarm  0 for false, 1 for true
			if(!(repeat_rule.equals(" ")))
			event.put("rrule",repeat_rule);	//number 0 no repeat, 1 daily, 2 weekly, 3 monthly, 4 yearly
			event.put("visibility",cmi.getReplication_status());//default (0), confidential (1), private (2), or public (3)
			
				
			
			Uri eventinsert=null,remindinsert=null;
			
			
			if(eventsUri!=null)
			 eventinsert = c.getContentResolver().insert(eventsUri, event);
			
			
			String[] proj = new String[] {"_id"};
			Cursor managedremCursor = c.getContentResolver().query(eventsUri, proj,"selected=1", null, null);
			
			String evId=null,evname=null;
			if (managedremCursor.moveToFirst()) 
			{
				//int namColumn = managedremCursor.getColumnIndex("name");
				int idColumn = managedremCursor.getColumnIndex("_id");
				 do {
				//	 evname = managedremCursor.getString(namColumn);
				    evId = managedremCursor.getString(idColumn);
				    Log.i("Meeting","in do-while loop eventId"+evId);
				    } while (managedremCursor.moveToNext());
			}
			else
			{
				Log.i("CalMeeting","No EventId's...");
			}
			Log.i("Meeting","After loop eventId:"+evId);
			
			
			Uri reminderUri = Uri.parse("content://calendar/reminders");
			ContentValues value = new ContentValues();
			value.put("event_id",evId);
			value.put("minutes", cmi.getAlarm_offset());	//alarm described as minutes before starttime
			if(reminderUri!=null)
			remindinsert =  c.getContentResolver().insert(reminderUri, value);
			
			Log.i("CalendarMeeting","eventUri:"+eventinsert);
			Log.i("CalendarMeeting","reminderUri:"+remindinsert);
		}//try
		catch(SQLException e)
		{
			throw new UserException(UserException.KErrFailedToAddRecord,e.getMessage());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new UserException(UserException.KErrGeneral,e.getMessage());	
		}
		return true;
		
	}
	public static boolean addCalendar_Memo(Context c,CalendarInfo cmi) throws  UserException
	{
		try
		{
			String[] projection = new String[] { "_id", "name" };
			
			Uri calendars = Uri.parse("content://calendar/calendars");
			String calId=null; 
			String calName=null;
			
			Cursor managedCursor = c.getContentResolver().query(calendars, projection,"selected=1", null, null);
			
			if (managedCursor.moveToFirst()) 
			{
				 
				 
				 int nameColumn = managedCursor.getColumnIndex("name"); 
				 int idColumn = managedCursor.getColumnIndex("_id");
				 do {
				    calName = managedCursor.getString(nameColumn);
				    calId = managedCursor.getString(idColumn);
				    
				    Log.i("Memo","in do-while loop calendarName:CalendarId:"+calName+":"+calId);
				 } while (managedCursor.moveToNext());
				 
			}
			else
			{
				Log.i("Memo","No Calendar Providers...");
			}


			
			
			
			
			 Log.i("Memo","After loop calendarName:CalendarId:"+calName+":"+calId);
			
			
			
			
			
			Uri eventsUri = Uri.parse("content://calendar/events");//Uri eventsUri = Uri.parse("android.provider.calendar.CONTENT_URI");
			ContentValues event = new ContentValues();
		
			String startTime = cmi.getStarttime();
			Log.i("Memo","startTime = "+startTime +"endTime = "+ cmi.getEndtime());
			DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
			Date date = (Date)formatter.parse(startTime);
			Long startdate = date.getTime();
			String endTime = cmi.getEndtime();
			Date date1 = (Date)formatter.parse(endTime);
			Long enddate = date1.getTime();
	       
			event.put("calendar_id",calId );
			event.put("title", cmi.getSubject());			//subject it is a string
			event.put("dtstart", startdate);				//start time <string dd-mm-yyyy tt:mm:ss>
			event.put("dtend", enddate);					//end time <string dd-mm-yyyy tt:mm:ss>
			event.put("visibility",cmi.getReplication_status());//default (0), confidential (1), private (2), or public (3)
			
			Uri memouri = null;
			if(eventsUri!=null)
			memouri = c.getContentResolver().insert(eventsUri, event);
			
			Log.i("Memo","eventUri:"+memouri);
			
			//Log.i("Add_Calender_Memo Under AH",""+url);
			 
		
			
		}//try
		catch(SQLException e)
		{
			throw new UserException(UserException.KErrFailedToAddRecord,e.getMessage());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			
			throw new UserException(UserException.KErrGeneral,e.getMessage());	
		}
		return true;
		
	}
	public static boolean addCalendar_Anniversary(Context c,CalendarInfo cmi) throws  UserException
	{
		try
		{
			String[] projection = new String[] { "_id", "name" };
			Uri calendars = Uri.parse("content://calendar/calendars");
			String calId=null; 
			 String calName=null;
			
			Cursor managedCursor = c.getContentResolver().query(calendars, projection,"selected=1", null, null);
			
			if (managedCursor.moveToFirst()) 
			{
				 
				 
				 int nameColumn = managedCursor.getColumnIndex("name"); 
				 int idColumn = managedCursor.getColumnIndex("_id");
				 do {
				    calName = managedCursor.getString(nameColumn);
				    calId = managedCursor.getString(idColumn);
				    
				    Log.i("Anniversary","in do-while loop calendarName:CalendarId:"+calName+":"+calId);
				 } while (managedCursor.moveToNext());
				 
			}
			else
			{
				Log.i("Anniversary","No Calendar Providers...");
			}
			
			 Log.i("Anniversary","after loop calendarName:CalendarId:"+calName+":"+calId);
			
			
			 
			 Uri eventinsert=null,remindinsert=null;
			
			
			 Uri eventsUri = Uri.parse("content://calendar/events");
			
			 		ContentValues event = new ContentValues();
	
			String alarm = cmi.getAlarm();
	        String startTime = cmi.getDate();
	        DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
			Date date = (Date)formatter.parse(startTime);
			Long startdate = date.getTime();
	        
			event.put("calendar_id", calId);
			event.put("title", cmi.getOccasion());			
			event.put("dtstart", startdate);	
			event.put("hasAlarm", alarm); 						
			event.put("visibility", cmi.getReplication_status());//default (0), confidential (1), private (2), or public (3)
			
			if(eventsUri!=null)	 
			 eventinsert = c.getContentResolver().insert(eventsUri, event);
			
			
			String[] proj = new String[] { "_id"};
			Cursor managedremCursor = c.getContentResolver().query(eventsUri, proj,"selected=1", null, null);
			
			String evId=null;
			if (managedremCursor.moveToFirst()) 
			 {
				 int idColumn = managedremCursor.getColumnIndex("_id");
				 do {
				    evId = managedremCursor.getString(idColumn);
				    Log.i("Anniversary","in do-while loop eventId:"+evId);
				 	} while (managedremCursor.moveToNext());
			}
			else
			{
				Log.i("Aniversary","No EventId's...");
			}
			
			Log.i("Anniversary","after loop eventId:"+evId);
			
			 Uri reminderUri = Uri.parse("content://calendar/reminders");
			 ContentValues value = new ContentValues();
			 value.put("event_id",evId);
			 value.put("minutes", cmi.getAlarm_offset());
			
			if(reminderUri!=null)
				remindinsert = c.getContentResolver().insert(reminderUri, value);
		
			Log.i("Anniversary","eventUri:"+eventinsert);
			Log.i("Anniversary","reminderUri:"+remindinsert);
		
			
		}//try
		catch(SQLException e)
		{
			throw new UserException(UserException.KErrFailedToAddRecord,e.getMessage());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			
			throw new UserException(UserException.KErrGeneral,e.getMessage());	
		}
		return true;
		
	}
	public static boolean localSMS(String sender,String sub,String text,Context c) throws UserException
	{
		try
		{
		
			ContentValues values = new ContentValues();
			values.put("address", sender);
			values.put("body", text);
			c.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
		
			NotificationManager nm = (NotificationManager)c.getSystemService(Context.NOTIFICATION_SERVICE);
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			
			//ComponentName comp = new ComponentName(com.android.mms,com.android.mms.ui.ComposeMessageActivity);
			//intent.setComponent(comp);
			
			//intent.setData(Uri.parse("content://mms-sms/conversations/1"));
			intent.setData(Uri.parse("content://mms-sms/conversations/1"));
			
			
			PendingIntent pendingIntent = PendingIntent.getActivity(c, 0, intent,Intent.FLAG_ACTIVITY_NEW_TASK);
			Notification notification = new Notification(R.drawable.icon, sender+":"+sub,System.currentTimeMillis());
			notification.setLatestEventInfo(c, sender, sub, pendingIntent);
			//notification.sound =  Uri.parse("android.resource://no.freedommedia.featurebooster.util/" +R.raw.love);
			
			notification.defaults |= Notification.DEFAULT_SOUND;
			notification.defaults |= Notification.DEFAULT_VIBRATE;
			
			nm.notify(1, notification);
	       
			
			
		}
		catch(SQLException e)
		{
			e.printStackTrace();	
			throw new UserException(UserException.KErrFailedToAddRecord,e.getMessage());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		return true;
	
	}

	
	public static PhoneInfo phoneInfo(Context c) throws UserException
	{
		
		PhoneInfo pi = new PhoneInfo();
		
		try
		{
			TelephonyManager imesi =  (TelephonyManager)c.getSystemService(Context.TELEPHONY_SERVICE);
			String MachineUid = imesi.getDeviceId();
			pi.setMachine_uid(MachineUid);
		
			
			
			File c_path = c.getFilesDir();
			StatFs c_stat = new StatFs(c_path.getPath());  
			long c_blockSize = c_stat.getBlockSize();  
			long c_availableBlocks = c_stat.getAvailableBlocks();
			long c_totalBlocks = c_stat.getBlockCount();
			long c_freeSize = c_availableBlocks * c_blockSize;
			long c_totalSize = c_totalBlocks * c_blockSize;
			
			String c_free = Long.toString(c_freeSize/(1024*1024)) + " MB";
			String c_size = Long.toString(c_totalSize/(1024*1024)) + " MB";
			
			pi.setDrive_c_free(c_free);
			pi.setDrive_c_size(c_size);
			
			
			File e_path = Environment.getExternalStorageDirectory();  
			StatFs e_stat = new StatFs(e_path.getPath());  
			long e_blockSize = e_stat.getBlockSize();  
			long e_totalBlocks = e_stat.getBlockCount();
			long e_availableBlocks = e_stat.getAvailableBlocks();
			long e_freeSize = e_availableBlocks * e_blockSize;
			long e_totalSize = e_totalBlocks * e_blockSize;
			
			
			String e_free = Long.toString(e_freeSize/(1024*1024)) + " MB";
			String e_size = Long.toString(e_totalSize/(1024*1024)) + " MB";
			
			pi.setDrive_e_free(e_free);
			pi.setDrive_e_size(e_size);
			
			
			
			
			
			
			ServiceState ss = new ServiceState();
		    
			int networkstatus = ss.getState();		//network status
			pi.setNetworkstatus(Integer.toString(networkstatus));
			
			
			int registration_status = ss.getState();
			pi.setRegistrationstatus(Integer.toString(registration_status));
			
			
		    Boolean networkmode = ss.getIsManualSelection();//network mode
		    pi.setNetworkmode(Boolean.toString(networkmode));
		    
		    String network_country_code = imesi.getNetworkCountryIso();
		    pi.setNetworkcountrycode(network_country_code);
		    
		    String network_id = imesi.getNetworkOperator();	//Use CdmaCellLocation.getnetworkid() here.
		    pi.setNetworkid(network_id);
		    
		    
		    String networkdispaly_tag = imesi.getSimOperatorName();
		    
		    pi.setNetworkdisplaytag(networkdispaly_tag);
		  
		    ConnectivityManager con = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE);
	    	
	    	NetworkInfo nwi = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	    	
	  
	    	String network_short_name = nwi.getSubtypeName();
	    	pi.setNetworkshortname(network_short_name);
	    	
	    	String network_bandinfo = nwi.getExtraInfo();
	    	pi.setNetworkbandinfo(network_bandinfo);
	    
	    	
	    	String cdmaSid = imesi.getSimSerialNumber();
			pi.setNetworkcdmasid(cdmaSid);
			
			/*CdmaCellLocation cd = (CdmaCellLocation) imesi.getCellLocation();
			cd.getsystemid();*/
			
			
			
	    
	    	String network_long_name = nwi.getTypeName();
	    	pi.setNetworklongname(network_long_name);
	    	
	    	int network_Access = nwi.getType();
	    	pi.setNetworkaccess(Integer.toString(network_Access));
	    	
	    	Boolean network_areaknow = nwi.isAvailable();
	    	pi.setNetworkareaknow(Boolean.toString(network_areaknow));
	    	
	    	String network_name = imesi.getNetworkOperatorName();
	    	pi.setNetworkname(network_name);
	    	
	    
	    	String operator_name = imesi.getNetworkOperatorName();
	    	pi.setOperatorname(operator_name);
	    	
	    	pi.setFbversion(GlobalProperties.version);
	    	
	    	int battery_status = BatteryLevel.status;
	    	pi.setBatterystatus(Integer.toString(battery_status));
	    	
	    	int battery_chargelevel = BatteryLevel.level;
	    	pi.setBatterychargelevel(Integer.toString(battery_chargelevel));
	    	
	    	//To be find signal strength,signal bar,indicator and indicator capabilities
	    	
	   
//	    	Log.i("get_phone_info under AH","Machine Id:"+MachineUid+"App free Size:"+c_free+"App Total size:"+c_size+"sdcard free size:"+e_free+"sdcard Total size:"+e_size);
//	    	Log.i("get_phone_info under AH","NetworkStatus:"+networkstatus+"Network Mode:"+networkmode+"Network country code:"+network_country_code+"Network Id:"+network_id+"Network short Name:"+network_short_name);
//	    	Log.i("get_phone_info under AH","NetworkLongName:"+network_long_name+"Network Access:"+network_Access+"Network are Known:"+network_areaknow);
//	    	Log.i("get_phone_info under AH","Network Name:"+network_name+"Battery Status:"+battery_status+"Battery charge Level:"+battery_chargelevel);

		}
		catch(ParseException pe)
		{
			throw new UserException(UserException.KErrAccessDenied,pe.getMessage());
		}
		
		catch(Exception e)
		{
		
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
    	return pi;
	
	}
	
	public static boolean saveBookmarks(String name,String url,Context context) throws UserException
	{
		try
		{
			if(name != null && url != null && context != null)
			{
				
				ContentValues values = new ContentValues();
				values.put(BookmarkColumns.TITLE,name);
				values.put(BookmarkColumns.URL,url);
				values.put(BookmarkColumns.VISITS,1);
				
				Calendar cal = Calendar.getInstance();
				int day = cal.get(Calendar.DATE);
				int month= cal.get(Calendar.MONTH);
				month++;
				int year = cal.get(Calendar.YEAR);
				String str =  Integer.toString(day)+"-"+Integer.toString(month)+"-"+ Integer.toString(year);
				values.put(BookmarkColumns.DATE,str);
				values.put(BookmarkColumns.BOOKMARK,1);
				values.put(BookmarkColumns.CREATED,0);
				
				context.getContentResolver().insert(Browser.BOOKMARKS_URI, values);
			}
			else
			{
				throw new UserException(UserException.KErrCdmaOtaInvalidParameter ,"  Invalid Parameters ");	
			}
			
		}
		catch(SQLException e)
		{
			throw new UserException(UserException.KErrInvalidDatabaseType,e.getMessage());
		}
		catch(Exception e)
		{
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		
		return true;
			
	}
	


		
//Create ShortCut
	
	
	public static boolean setShortCut(String appName,Context context) throws UserException
    {
    	
		try
		{
		 //Log.i("shortcut method in androidhelper start","in the shortcutapp on create method ");
         boolean flag =false ;
         int app_id=-1;
         PackageManager p = context.getPackageManager();
 		 Intent i = new Intent(Intent.ACTION_MAIN);
 		 i.addCategory(Intent.CATEGORY_LAUNCHER); 
 	     List<ResolveInfo> res =p.queryIntentActivities( i,0);
 		 //System.out.println("the res size  is: "+res.size());
 	    
	 	    for(int k=0;k<res.size();k++)
	 	    {
	 	    	//Log.i("","the application name is: "+res.get(k).activityInfo.loadLabel(p));
	 	    	if(res.get(k).activityInfo.loadLabel(p).toString().equals(appName)){
	 	    		flag = true;
	 	    		app_id = k;
	 	    		break;
	 	    	}
	 	    }
 	        
	 	    if(flag)
	 	    {
		 	    ActivityInfo ai = res.get(app_id).activityInfo;
		 	    Intent shortcutIntent = new Intent();
		 	    shortcutIntent.setClassName(ai.packageName, ai.name);
		 	    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		 	    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		 	    shortcutIntent.addCategory(Intent.ACTION_PICK_ACTIVITY);
		 	    Intent intent = new Intent();
		 	    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		 	    // Sets the custom shortcut's title
		 	    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
		 	    
		 	      BitmapDrawable bd=(BitmapDrawable)(res.get(app_id).activityInfo.loadIcon(p).getCurrent());
			 	  Bitmap newbit;
			 	  newbit=bd.getBitmap();
			 	  intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, newbit);

		 	    intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		 	    context.sendBroadcast(intent);
		 	    
	 	    }
	 	    else
	 	    {
	 	    	throw new UserException(UserException.KErrGeneral,"Application not found");
	 	    }
		
		}
		
		catch(ActivityNotFoundException e)
		{
			e.printStackTrace();
			throw new UserException(UserException.KErrGsmRRNoActivityOnRadioPath,e.getMessage());	
		}
		
		
		catch(Exception e)
		{
			e.printStackTrace();
			throw new UserException(UserException.KErrGeneral,e.getMessage());
				
		}
		return true;
    }
	

	

	
	public  static boolean setRingTone(String file,String filepath,Context c) throws UserException
	{
		try
		{
		 //String filepath ="/sdcard/play2.mp3";
			File ringtoneFile = new File(filepath);
			
			ContentValues content = new ContentValues();
			content.put(MediaStore.MediaColumns.DATA, ringtoneFile.getAbsolutePath());
			content.put(MediaStore.MediaColumns.TITLE,file );
			//content.put(MediaStore.MediaColumns.SIZE, 215454);
			content.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
			//content.put(MediaStore.Audio.Media.ARTIST, "Madonna");
			//content.put(MediaStore.Audio.Media.DURATION, 230);
			content.put(MediaStore.Audio.Media.IS_RINGTONE, true);
			content.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
			//content.put(MediaStore.Audio.Media.IS_ALARM, false);
			//content.put(MediaStore.Audio.Media.IS_MUSIC, false);
			

			//Insert it into the database
		    Uri uri = MediaStore.Audio.Media.getContentUriForPath(ringtoneFile.getAbsolutePath());
			Uri newUri = c.getContentResolver().insert(uri, content);
			
			//set ringtone
	    	RingtoneManager.setActualDefaultRingtoneUri(c,RingtoneManager.TYPE_RINGTONE,newUri);
		}
		catch(Exception e)
		{
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		return true;
	}
	
//Query 
	
	public static int alertbox(final String title, final String mymessage,final ArrayList <String> softkeyvalue,final Context context)  
	{
			
		    Log.i("Android Helper","sending values are "+title+ mymessage+ softkeyvalue);
		  	
	   
		    Intent i1 = new Intent(context, MyAlertBox.class);
			
	 	    i1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	 	  
	 	    i1.putExtra("title", title);
	        i1.putExtra("message", mymessage);
	 	    i1.putStringArrayListExtra("buttonNames", softkeyvalue);
	  
	        context.startActivity(i1);
	   
	     
			return MyAlertBox.status;
		}
	

	
	public  static boolean installApp(String filepath,Context c) throws UserException
	{
		try
		{ 
			Log.i("file path in install app",""+filepath);
			Intent intent = new Intent();
			//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        intent.setAction(android.content.Intent.ACTION_VIEW);
	        File file = new File(filepath);
	        Process  p = Runtime.getRuntime().exec("chmod 777 " + file);
	        Log.i("install AH","Before Sleep");
	        Thread.sleep(5000);
	        Log.i("install","After Sleep");
	        //FilePermission fp = new FilePermission(filepath, "read,write,execute");
	        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
	        c.startActivity(intent);
	        Log.i("install AH","After Calling startActivity...");
	        Thread.sleep(15000);
	        Log.i("install AH","After Long Sleep...");  
	 	}
		
		catch(Exception e)
		{
			e.printStackTrace();
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		return true;
	}
	public static boolean updateApp(String filePath,Context c) throws UserException
	{
		try
		{
			 Intent intent = new Intent("com.fireice.fb");
			 
			 Process  p = Runtime.getRuntime().exec("chmod 777 " + filePath);
			 intent.putExtra("filepath",filePath);
			   
			 c.sendBroadcast(intent);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		return true;
	}
	
	public  static boolean runApp(String filepath,Context c) throws UserException
	{
		try
		{
			
			//Process process = Runtime.getRuntime().exec(filepath);
			
			PackageManager p = c.getPackageManager();
			
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER); 
		    List<ResolveInfo> res =p.queryIntentActivities( intent,0);

		    for(int ii=0;ii<res.size();ii++)
		    {
		    	
		    	if( res.get(ii).activityInfo.loadLabel(p).equals(filepath))
		    	{
		    		
		    		intent.setClassName(res.get(ii).activityInfo.packageName, res.get(ii).activityInfo.name);  
		    		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    		c.startActivity(intent);
		    		
		    		return true;
		    	}
		    }
		    	   
		
		}
		
		catch(Exception e)
		{
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		return false;
	}
	public  static boolean addPop3Account(EmailInfo ei,Context c) throws UserException
	{
		try
		{
			
			
		}
		
		catch(Exception e)
		{
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		return false;
	}
	public  static boolean addImap4Account(EmailInfo ei,Context c) throws UserException
	{
		try
		{
		
		}
	
		catch(Exception e)
		{
			throw new UserException(UserException.KErrGeneral,e.getMessage());
		}
		return false;
	}
	}
	 