<?php

include_once __DIR__ . '/BaseInventoryWidget.php';

class BarPieChart implements BaseInventoryWidget
{
    public function getStatistics($name, HttpClientInterface $restClient, $filters = []) : array
    {
        $dataToApi = [
            'select' => [$name],
            'limit' => -1,
            ...$filters
        ];

        $attributes = json_decode($restClient->get('/inventory/attributes-dictionary'), JSON_OBJECT_AS_ARRAY);
        //find array's index of attribute
        $index = array_search($name, array_column($attributes, 'attribute_name'));
        $attributeType = $index !== false ? $attributes[$index]['type'] : '';

        /**
         * @todo ENT-9932: return numbers from the db instead of counting them in code
         */
        $response = $restClient->post('/inventory', $dataToApi);
        $response = json_decode($response, JSON_OBJECT_AS_ARRAY);
        $data = $response["data"][0]['rows'];
        $result = [];

        foreach ($data as $row) {
            //if attribute type is slist then split value by comma
            if ($attributeType == 'slist') {
                $result = array_merge($result, explode(',', $row[0]));
            } else {
                $result[] = strval($row[0]);
            }
        }

        $result = array_map(function ($value) {
            return empty($value) ? false : trim($value);
        }, $result);

        // remove values that are not string or int as array_count_values accepts only these types
        $result = array_filter($result, function ($value) {
            return is_string($value) || is_int($value);
        });

        $return = array_count_values($result);
        uksort($return, 'strcasecmp');
        return $return;
    }

}
