<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace LifeStyle\DH\AccessControlBundle\Repository;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use LifeStyle\DH\AccessControlBundle\Exception\InvalidRequestException;

/**
 * Class ObjectServiceRepository
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package LifeStyle\DH\AccessControlBundle\Repository
 */
class ObjectServiceRepository
{
    /**
     * @var ClientInterface
     */
    private $client;

    /**
     * ObjectServiceRepository constructor.
     * @param ClientInterface $client
     */
    public function __construct(ClientInterface $client)
    {
        $this->client = $client;
    }

    /**
     * @param array $scopeIds
     * @return array
     * @throws InvalidRequestException
     */
    public function findObjectIdsByScopeIds(array $scopeIds): array
    {
        if (empty($scopeIds)) {
            return [];
        }

        $documentIds = array_map(
            [$this, 'quoteMongoId'],
            array_filter(
                $scopeIds,
                [$this, 'isMongoId']
            )
        );

        $options = [
            'body' => '{
  "skip": 0,
  "limit": 0,
  "child_depth": 0,
  "attributes_depth": 0,
  "query_aggregate": [
    {
      "$project": {
        "_id" : "$_id",
        "in_scopes" : {
          "$in": [ "$_id", [' . implode(',', $documentIds) . '] ]
        }
      }
    },
    {
      "$match": {
        "in_scopes": true
      }
    },
    {
      "$graphLookup": {
        "from": "object_documents",
        "startWith": "$_id",
        "connectFromField": "_id",
        "connectToField": "parent",
        "as": "children",
        "maxDepth": 10,
        "depthField": "depthField"
      }
    },
    {
      "$unwind": "$children"
    },
    {
      "$replaceRoot": {
        "newRoot": "$children"
      }
    },
    {
      "$project":  {
        "_id": "$_id"
      }
    }
  ],
  "order_by": {
    "tree_id": -1
  }
}'
        ];
        try {
            $response = $this->client->request('POST', '/api/document/object/search', $options);
        } catch (GuzzleException $exception) {
            throw new InvalidRequestException('Invalid object-ws request! ' . $exception->getMessage(), 500, $exception);
        }

        $result = json_decode($response->getBody()->getContents(), true);

        // Merge scopes into result
        return array_merge(
            isset($result['aggregate_result']) ? array_map(
                function ($item) {
                    return $item['_id'];
                },
                $result['aggregate_result']
            ) : [],
            $scopeIds
        );
    }

    /**
     * @param string $id
     * @return string
     */
    private function quoteMongoId(string $id): string
    {
        return '"MongoId(\'' . $id . '\')"';
    }

    /**
     * @param string $id
     * @return bool
     */
    private function isMongoId(string $id): bool
    {
        return preg_match('/^[a-f0-9]+$/', $id) && 24 === strlen($id);
    }
}
