<?php

namespace Teknisa\Libs\Util;

class IntegrationProvider implements \Zeedhi\Framework\Security\OAuth\ServiceProvider
{

    private $services = array();

    public function __construct() {
        $clientServices = $this->readJson();
        foreach ($clientServices as $clientService) {
            $this->services[] = new Integration($clientService['name'], $clientService['clientId'],
                $clientService['clientSecret'], $clientService['nrOrg'], $clientService['cdOperator']);
        }
    }

    public function findByClientAndSecretId($clientId, $clientSecret) {
        foreach ($this->services as $service) {
            if ($service->getClientId() === $clientId && $service->getClientSecret() === $clientSecret) {
                return $service;
            }
        }
        return null;
    }

    private function readJson() {
        $json = file_get_contents(__DIR__ . "/../../../../config/integration.json");
        $integrations = json_decode($json, true);
        $productIntegrations = @file_get_contents(Utilities::getProductBasePath() . "/backend/config/integration.json");
        if(!empty($productIntegrations)) {
            $integrations = array_merge($integrations, json_decode($productIntegrations, true));
        }
        return $integrations;
    }
}