<?php

/**
 * Class File_integrity_monitoring_model
 */
class File_integrity_monitoring_model extends Cf_Model
{
    /**
     * @param $name
     * @param $limit
     * @return array
     */
    public function getFilesList($name, $limit)
    {
        $params = [];

        if ($name != null) {
            $params['query'] = $name;
        }

        if ($limit != null) {
            $params['limit'] = $limit;
        }

        $files = json_decode(
            $this->getRestClient()->get('/file-changes/files?' . http_build_query($params)),
            JSON_OBJECT_AS_ARRAY,
        );

        // get directories in case of unix agent
        $directories = $this->addDirectoriesFromFiles($files, '/');
        // get directories in case of windows agent
        $directories = array_merge($directories, $this->addDirectoriesFromFiles($files, '\\'));
        $directoriesCount = array_count_values($directories);

        /**
         * Remove directories that appear once
         * Makes no sense to filter by directory if only one file in that path
         */
        $directories = array_filter($directories, function ($value) use ($directoriesCount) {
            return $directoriesCount[$value] > 1 ? true : false;
        });

        $result = array_unique(array_merge($files, $directories));
        arsort($result);
        return array_values($result);
    }

    /**
     * parse files and build directories for filter
     * /etc/cfengine/masterfiles/main.cf => [/etc/, /etc/cfengine/, /etc/cfengine/masterfiles/]
     */
    private function addDirectoriesFromFiles(iterable $files, $directorySeparator)
    {
        $result = [];

        foreach ($files as $file) {
            $filePathParts = explode($directorySeparator, $file);

            for ($i = 1; sizeof($filePathParts) > $i; $i++) {
                array_pop($filePathParts);
                $result[] = implode($directorySeparator, $filePathParts) . $directorySeparator;
            }
        }
        return $result;
    }
}
