<?php
// src/OgBootBundle/Service/CurlRequestService.php

namespace App\OgBootBundle\Service;
use Exception;
use Psr\Log\LoggerInterface;

class CurlRequestService
{

    public function convertMaskToCIDR($mask)
    {
        $bits = 0;
        $mask = explode(".", $mask);

        foreach ($mask as $octect)
            $bits += strlen(str_replace("0", "", decbin($octect)));

        return $bits;
    }

// src/Service/CurlRequestService.php

public function installOglive($isoname)
{
    $socketPath = '/tmp/oglive_daemon.sock';
    $socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
    if ($socket === false) {
        syslog(LOG_ERR, 'Error al crear el socket: ' . socket_strerror(socket_last_error()));
        return ['success' => false, 'output' => 'Error al crear el socket'];
    }

    $result = socket_connect($socket, $socketPath);
    if ($result === false) {
        syslog(LOG_ERR, 'Error al conectar con el socket: ' . socket_strerror(socket_last_error($socket)));
        socket_close($socket);
        return ['success' => false, 'output' => 'Error al conectar con el socket'];
    }

    $command = [
        'action' => 'download',
        'args' => [$isoname]
    ];

    socket_write($socket, json_encode($command), strlen(json_encode($command)));

    $response = '';
    $status = [];

    while ($buffer = socket_read($socket, 2048)) {
        $response .= $buffer;
        $status[] = json_decode($buffer, true);
    }

    socket_close($socket);

    // Analiza el último estado recibido
    $lastStatus = end($status);
    if ($lastStatus && $lastStatus['status'] === 'completed') {
        return ['success' => true, 'output' => $lastStatus];
    } else {
        return ['success' => false, 'output' => $status];
    }
}



public function callOgLive($parameter)
{
    $socketPath = '/var/run/oglive/oglive_daemon.sock';
    
    file_put_contents('/tmp/serviceOglive.log', 'callOgLive called with parameter: ' . $parameter . PHP_EOL, FILE_APPEND);
    
    $socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
    if ($socket === false) {
        $error = 'Error al crear el socket: ' . socket_strerror(socket_last_error());
        file_put_contents('/tmp/serviceOglive.log', 'Socket creation error: ' . $error . PHP_EOL, FILE_APPEND);
        return [
            'success' => false,
            'error' => $error
        ];
    }

    $result = socket_connect($socket, $socketPath);
    if ($result === false) {
        $error = 'Error al conectar con el socket: ' . socket_strerror(socket_last_error($socket));
        file_put_contents('/tmp/serviceOglive.log', 'Socket connection error: ' . $error . PHP_EOL, FILE_APPEND);
        socket_close($socket);
        return [
            'success' => false,
            'error' => $error
        ];
    }

    $args = array_map('trim', explode(' ', $parameter));
    $action = array_shift($args);
    $command = [
        'action' => $action,
        'args' => $args
    ];

    socket_write($socket, json_encode($command), strlen(json_encode($command)));

    $response = '';
    while ($buffer = socket_read($socket, 2048)) {
        $response .= $buffer;
    }

    socket_close($socket);

    file_put_contents('/tmp/serviceOglive.log', 'Raw response: ' . $response . PHP_EOL, FILE_APPEND);

    if (empty($response)) {
        $error = 'Respuesta vacía del demonio';
        file_put_contents('/tmp/serviceOglive.log', 'Empty response error: ' . $error . PHP_EOL, FILE_APPEND);
        return [
            'success' => false,
            'error' => $error
        ];
    }

    $decodedResponse = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        $error = 'Error al decodificar JSON: ' . json_last_error_msg();
        file_put_contents('/tmp/serviceOglive.log', 'JSON decode error: ' . $error . PHP_EOL, FILE_APPEND);
        return [
            'success' => false,
            'error' => $error
        ];
    }

    if (isset($decodedResponse['success']) && $decodedResponse['success']) {
        file_put_contents('/tmp/serviceOglive.log', 'Decoded successful response: ' . json_encode($decodedResponse['output']) . PHP_EOL, FILE_APPEND);
        return $decodedResponse['output'];
    } else {
        $error = $decodedResponse['error'] ?? 'Unknown error';
        file_put_contents('/tmp/serviceOglive.log', 'Error in response: ' . $error . PHP_EOL, FILE_APPEND);
        return [
            'success' => false,
            'error' => $error
        ];
    }
}




}
