<?php
require_once APPPATH . 'libraries/Cf_REST_Controller.php';

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

    public function items_get($groupId)
    {
        try {
            $list = $this->sharedGroupCmdb_model->getItem($groupId);
            $this->respond(200, json_encode($list));
            return;
        } catch (Exception $exception) {
            log_message('error', "Unable to get group data for shared group #$groupId. Error: " . $exception->getMessage());
            throw $exception;
        }
    }

    public function item_post($groupId, $type, $name)
    {
        try {
            $data = json_decode($_REQUEST['data'], true);
            $list = $this->sharedGroupCmdb_model->createItem($groupId, $type, $name, $data);
            $this->respond(200, json_encode($list));
            return;
        } catch (Exception $exception) {
            log_message('error', "Unable to update group data for shared group #$groupId. Error: " . $exception->getMessage());
            throw $exception;
        }
    }

    public function item_put($groupId, $type, $name)
    {
        try {
            preg_match('/data=(.*)$/', $this->_put_args, $matches);
            $data = json_decode(urldecode($matches[1]), true);
            $list = $this->sharedGroupCmdb_model->updateItem($groupId, $type, $name, $data);
            $this->respond(200, json_encode($list));
            return;
        } catch (Exception $exception) {
            log_message('error', "Unable to update group data for shared group #$groupId. Error: " . $exception->getMessage());
            throw $exception;
        }
    }

    public function item_get($groupId, $type, $name)
    {
        try {
            $list = $this->sharedGroupCmdb_model->getItemByName($groupId, $type, $name);
            $this->respond(200, json_encode($list));
            return;
        } catch (HttpClient_NotFound $exception) {
            $this->respond(404);
        } catch (Exception $exception) {
            log_message('error', "Unable to get group data item for shared group #$groupId. Error: " . $exception->getMessage());
            throw $exception;
        }
    }

    public function item_delete($groupId, $type, $name)
    {
        try {
            $list = $this->sharedGroupCmdb_model->deleteItem($groupId, $type, $name);
            $this->respond(200, json_encode($list));
            return;
        } catch (Exception $exception) {
            log_message('error', "Unable to delete group data item for shared group #$groupId. Error: " . $exception->getMessage());
            throw $exception;
        }
    }
}
