package pb.project.picamera;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class CommService extends Service {

	private static final int SERVERPORT = 5000;
	private Socket socket;
	private String ipAddress;
	
	@Override
	public IBinder onBind(Intent intent) {
		ipAddress = intent.getExtras().getString("ipAddr");
		Log.d("service", "onbind");
		return myBinder;
	}
	
	private final IBinder myBinder = new LocalBinder();

	public class LocalBinder extends Binder {
        public CommService getService() {
            System.out.println("I am in Localbinder ");
            return CommService.this;

        }
    }
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		//Log.d("service", "onstart");
		if (intent != null && intent.getExtras() != null){
			ipAddress = intent.getExtras().getString("ipAddr");
		
			new Thread(new ClientThread(ipAddress)).start();
		}
		return START_STICKY;
	}
	
	class ClientThread implements Runnable {

		String ipAddress;
		public ClientThread(String ipAddress) {
			this.ipAddress = ipAddress;
		}
		
		@Override
		public void run() {
			String response = "";
			try {
				Log.d("service", "thread run");
			    socket = new Socket(ipAddress, SERVERPORT);
			    
			    ByteArrayOutputStream byteArrayOutputStream = 
			                  new ByteArrayOutputStream(1024);
			    byte[] buffer = new byte[1024];
			    
			    int bytesRead;
			    InputStream inputStream = socket.getInputStream();
			    
			    /*
			     * notice:
			     * inputStream.read() will block if no data return
			     */
			             while ((bytesRead = inputStream.read(buffer)) != -1){
			                 byteArrayOutputStream.write(buffer, 0, bytesRead);
			                 response += byteArrayOutputStream.toString("UTF-8");
			                 Log.i("nic", "respo:"+response);
			                 if (response.equals("run")){
			                	 try {
		                		    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		                		    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
		                		    r.play();
		                		} catch (Exception e) {
		                		    e.printStackTrace();
		                		}
			                	 Log.d("service", "zvonííííííím");
			                	 NotificationManager notificationManager =
			                			    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			                	 
			                	 PendingIntent pendingIntent = PendingIntent.getActivity(CommService.this, 0, new Intent(CommService.this, MainActivity.class), 0);
			                	 
			                			Notification notification = new NotificationCompat.Builder(CommService.this)
			                            .setContentTitle("piCamera")
			                            .setContentText("Nìkdo zvoní :)").setSmallIcon(R.drawable.ic_launcher)
			                            .setContentIntent(pendingIntent)
			                            .build();
			                			
			                			notificationManager.notify(0, notification);
			                	 response = "";
			                	 byteArrayOutputStream.reset();
			                 }
			             }
		   } catch (UnknownHostException e) {
			    e.printStackTrace();
			    response = "UnknownHostException: " + e.toString();
		   } catch (IOException e) {
			    e.printStackTrace();
			    response = "IOException: " + e.toString();
		   }finally{
			   if(socket != null){
				   try {
					   socket.close();
				   } catch (IOException e) {
					   e.printStackTrace();
				   }
			   }
		   }

		}

	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        socket = null;
	}
	
}
