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

class SharedGroups extends Cf_REST_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('groups_app/shared_groups_model');
    }

    public function list_get()
    {
        try {
            $groups = json_decode($this->shared_groups_model->list($_GET), true);
            $groups['data'] = array_map(function ($group) {
                $group['meta_data'] = json_decode($group['meta_data'], true);
                $group['name'] = html_entity_decode($group['name']);
                return $group;
            }, $groups['data']);
        } catch (Exception $exception) {
            log_message('error', 'Unable to get list of shared groups. Error: ' . $exception->getMessage());
            throw $exception;
        }
        $this->respond(200, json_encode($groups));
    }

    public function group_delete($id)
    {
        try {
            $result = $this->shared_groups_model->remove($id);
            $this->respond(200, $result);
        } catch (Exception $exception) {
            log_message('error', "Unable to remove shared group #$id. Error:  {$exception->getMessage()}");
            throw $exception;
        }
    }

    public function group_get($id)
    {
        try {
            $group = json_decode($this->shared_groups_model->get($id), true);
            $group['name'] = html_entity_decode($group['name']);
            $group['filter'] = recursiveHtmlEntityDecode($group['filter']);
            $this->respond(200, json_encode($group));
        } catch (HttpClient_NotFound $exception) {
            $this->respond(404);
        } catch (Exception $exception) {
            log_message('error', "Unable to get shared group #$id. Error: {$exception->getMessage()}");
            throw $exception;
        }
    }

    public function group_put($id)
    {
        try {
            $data = json_decode($this->_put_args, true);
            $group = $this->shared_groups_model->update($id, $data);
            $this->respond(200, $group);
        } catch (HttpClient_NotFound $exception) {
            $this->respond(404);
        } catch (Exception $exception) {
            log_message('error', "Unable to update shared group #$id. Error: {$exception->getMessage()}");
            throw $exception;
        }
    }

    public function new_group_post()
    {
        $defaultName = 'New Group';
        try {
            // get group to identify next available ID
            $group = json_decode($this
                ->shared_groups_model
                ->list(
                    [
                        'searchQuery' => $defaultName,
                        'sortColumn' => 'nameIntSort',
                        'sortDescending' => 'true',
                        'limit' => 1
                    ]
                ), true);

            if (!empty($group) && !empty($group['data'])) {
                preg_match('/\d+$/', $group['data'][0]['name'], $matches);
                $nextNumber = intval($matches[0]) + 1;
                $defaultName .= ' ' . $nextNumber;
            }

            $newGroup = $this->shared_groups_model->create(['name' => $defaultName, 'filter' => []]);
            $this->respond(200, $newGroup);
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), 'Unexpected error while creating group. ' . $e->getTraceAsString());
            $this->respond(500, $e->getMessage());
        }
    }

    public function group_post()
    {
        try {
            $data = json_decode($this->request->body, true);
            $group = $this->shared_groups_model->create($data);
            $this->respond(200, $group);
        } catch (HttpClient_NotFound $exception) {
            $this->respond(404);
        } catch (Exception $exception) {
            log_message('error', 'Unable to create shared group. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }

    public function makePersonal_post($id)
    {
        try {
            $response = $this->shared_groups_model->makePersonal($id);
            $this->respond(200, $response);
        } catch (HttpClient_NotFound $exception) {
            $this->respond(404);
        } catch (Exception $exception) {
            log_message('error', "Unable to make group #$id personal. Error: {$exception->getMessage()}");
            throw $exception;
        }
    }

    public function favorite_delete($id)
    {
        try {
            $result = $this->shared_groups_model->removeFromFavorites($id);
            $this->respond(200, $result);
        } catch (Exception $exception) {
            log_message(
                'error',
                "Unable to remove shared group #$id from favorites. Error: {$exception->getMessage()}"
            );
            throw $exception;
        }
    }

    public function favorite_post($id)
    {
        try {
            $result = $this->shared_groups_model->addToFavorites($id);
            $this->respond(200, $result);
        } catch (Exception $exception) {
            log_message(
                'error',
                "Unable to add shared group #$id to favorites. Error: {$exception->getMessage()}"
            );
            throw $exception;
        }
    }

}
