<?php

require_once APPPATH . 'libraries/Cf_REST_Controller.php';
require_once APPPATH . 'models/Entities/CF_ContainerListArguments.php';
require_once APPPATH . 'models/Entities/CF_ContainerImageListArguments.php';
require_once APPPATH . 'models/Entities/CF_ContainerVolumeListArguments.php';

class Containers extends Cf_REST_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('containers_model');
    }

    public function list_get()
    {
        try {
            $arguments = CF_ContainerListArguments::fromArray($_REQUEST);
            $response = $this->containers_model->listContainers($arguments);
            respond_ok(json_encode($response), total: $response['meta']['total'] ?? null);
        } catch (Exception $exception) {
            log_message('error', 'Unable to list containers. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }

    public function images_get()
    {
        try {
            $arguments = CF_ContainerImageListArguments::fromArray($_REQUEST);
            $response = $this->containers_model->listImages($arguments);
            respond_ok(json_encode($response), total: $response['meta']['total'] ?? null);
        } catch (Exception $exception) {
            log_message('error', 'Unable to list container images. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }

    public function volumes_get()
    {
        try {
            $arguments = CF_ContainerVolumeListArguments::fromArray($_REQUEST);
            $response = $this->containers_model->listVolumes($arguments);
            respond_ok(json_encode($response), total: $response['meta']['total'] ?? null);
        } catch (Exception $exception) {
            log_message('error', 'Unable to list container volumes. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }

    public function summary_get($hostkey)
    {
        try {
            $summary = $this->containers_model->summary($hostkey);
            respond_ok(json_encode($summary));
        } catch (HttpClient_NotFound $exception) {
            respond_not_found();
        } catch (Exception $exception) {
            log_message('error', 'Unable to get containers summary. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }
}
