<?php

namespace QueryL10n;

// Autoloading of composer dependencies
$root_folder = realpath(__DIR__ . '/../..');
require_once "{$root_folder}/vendor/autoload.php";
$source_path = "{$root_folder}/app/sources/";
$repos = new Repositories($source_path);
$available_repositories = $repos->getRepositories();
$errors = [];
// Check if there are duplicated display_order values
$order = [];
foreach ($available_repositories as $repo_data) {
    $repo_order = $repo_data['display_order'];
    if ($repo_order == 0) {
        continue;
    }
    if (!in_array($repo_order, $order)) {
        $order[] = $repo_order;
    } else {
        $errors[] = "Repository *{$repo_data['id']}* has a duplicated display_order ({$repo_order})";
    }
}
// Check if display_order values are not sequential
sort($order);
for ($i = 0; $i < count($order) - 1; $i++) {
    if ($order[$i] + 1 != $order[$i + 1]) {
        $errors[] = "display_order value is not sequential ({$order[$i + 1]})";
    }
}
// Autoloading of composer dependencies
require_once __DIR__ . '/vendor/autoload.php';
$source_path = __DIR__ . '/sources/';
// Query request
$type = Utils::getQueryParam('type');
$repo = Utils::getQueryParam('repo');
$bugzilla = Utils::getQueryParam('bugzilla');
$repos = new Repositories($source_path);
$json_data = new Json();
// Only one repo requested
if ($repo != '') {
    $locales = $repos->getSingleRepository($repo);
    if ($locales) {
        die($json_data->outputContent($locales));
    } else {
        http_response_code(400);
        die('ERROR: unknown repository.');
    }
}
// Only one type of repo requested
if ($type != '') {
    die($json_data->outputContent($repos->getTypeRepositories($type)));
}
// Bugzilla components
if ($bugzilla != '') {
    $bugzilla_query = new Bugzilla($source_path);
    die($json_data->outputContent($bugzilla_query->getBugzillaComponents($bugzilla)));
}
// Display a list of all repositories
die($json_data->outputContent($repos->getRepositories()));