<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Chat extends CI_CONTROLLER
{
    
    function __construct() 
    {
        parent::__construct();
    }
    
    public function index()
    {
        
        log_message('INFO','--------------------------------> START AWS <-------------------------------------------');
        
        // Fetch the raw POST body containing the message
        $postBody = file_get_contents('php://input');
        
        // JSON decode the body to an array of message data
        $message = json_decode($postBody, true);
        if ($message) {
            // Do something with the data
            log_message('INFO','POST -> '.json_encode($message));
        }
        else {
            log_message('INFO',' foi triste ');
        }
        
        
        
        
        // Instantiate the Message and Validator
        $message = Message::fromRawPostData();
        $validator = new MessageValidator();
        
        // Validate the message and log errors if invalid.
        try {
          $res = $validator->validate($message);
           
           
            log_message('INFO',json_encode($res));
           
        } catch (InvalidSnsMessageException $e) {
           // Pretend we're not here if the message is invalid.
           http_response_code(404);
           error_log('SNS Message Validation Error: ' . $e->getMessage());
           die();
        }
        
        // Check the type of the message and handle the subscription.
        if ($message['Type'] === 'SubscriptionConfirmation') {
           // Confirm the subscription by sending a GET request to the SubscribeURL
           file_get_contents($message['SubscribeURL']);
        }
    }
    
    public function confirmation()
    {
        // Fetch the raw POST body containing the message
        $postBody = file_get_contents('php://input');
        
        // JSON decode the body to an array of message data
        $message = json_decode($postBody, true);
        
        if(isset($message['SubscribeURL']) && !empty($message['SubscribeURL']))
        {
            file_get_contents($message['SubscribeURL']);
        }
    }
    


    /*public function index()
	{
		$this->load->view('chat_task');
	}*/
	
	public function get_message()
	{
		header('Content-Type: text/event-stream');
		// recommended to prevent caching of event data.
		header('Cache-Control: no-cache');
			
		function send_message($id, $message, $progress) {
			$d = array('message' => $message , 'progress' => $progress);
				
			echo "id: $id" . PHP_EOL;
			echo "data: " . json_encode($d) . PHP_EOL;
			echo PHP_EOL;
				
			ob_flush();
			flush();
		}
			
			
		 //LONG RUNNING TASK
		for($i = 1; $i <= 10; $i++) {
			send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
				
			sleep(1);
		} 
		
		//$this->update_municipio_junto();
			
		send_message('CLOSE','Process complete',100);
	}
	
	public function server()
	{
	    // set some variables // 123 // 444
        $host = "127.0.0.1";
        $port = 0;
        // don't timeout!
        set_time_limit(0);
        // create socket
        $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
        // bind socket to port
        $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
        // start listening for connections
        $result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
        
        // accept incoming connections
        // spawn another socket to handle communication
        $spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
        // read client input
        $input = socket_read($spawn, 1024) or die("Could not read input\n");
        // clean up input string
        $input = trim($input);
        echo "Client Message : ".$input;
        // reverse client input and send back
        $output = strrev($input) . "\n";
        socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
        // close sockets
        socket_shutdown($socket, 2);
        socket_close($spawn);
        socket_close($socket);
	}
	
	public function client(){
	    $host    = "0.0.0.0";
        $port    = 5556;
        $message = "Hello Server";
        echo "Message To server :".$message;
        // create socket
        $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
        // connect to server
        $result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
        // send string to server
        socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
        // get server response
        $result = socket_read ($socket, 1024) or die("Could not read server response\n");
        echo "Reply From Server  :".$result;
        // close socket
        socket_close($socket);
	}
	
	public function ingow()
	{
	    echo phpinfo();
	}
}