<?php

require dirname(__FILE__).'/../common.php';
require dirname(__FILE__).'/../lib/auth.php';

use Symfony\Component\HttpClient\HttpClient;
use Doctrine\Exception\ConstraintViolationException;

$query_string='author:"Lavaux, G" OR "Lavaux, Guilhem"';

if (!empty($_GET['year'])) {
    $query_string = $query_string . ' year:' . intval($_GET['year']);
}

if (!empty($_GET['update'])) {
    $update = boolval($_GET['update']);
} else {
    $update = false;
}

## Create pattern for querying ADS
$ADS_URL = 'https://api.adsabs.harvard.edu/v1/search/query?q='.urlencode($query_string).'&fl=id,date,identifier,year,doctype,author,eprint,doi,title,bibcode,citation_count,pub,pubdate,page,volume&rows=300';

$client = HttpClient::create([
  'headers' => [
    'Authorization' => 'Bearer:' . $ADS_TOKEN
  ]
]);

try {
    $response = $client->request('GET', $ADS_URL);

    $statusCode = $response->getStatusCode();
    if ($statusCode != 200) {
        $result = ['result' => '0', 'original_code' => $statusCode];
        echo json_encode($result);
        exit(200);
    }
} catch (\Symfony\Component\HttpClient\Exception\TransportException $e) {
    return_error($e);
}

$contentType = $response->getHeaders()['content-type'][0];
if ($contentType != 'application/json') {
    $result = ['result' => '0', 'original_content' => $contentType];
    echo json_encode($result);
    exit(200);
}

# Transform the returned JSON into a PHP array
$content = $response->toArray();


# Now ready to inject the result into own DB
$data_insert=new ArrayObject(array());
try {
    foreach ($content['response']['docs'] as $doc) {
        $db_conn->beginTransaction();
        try {
            $schema->insertPublication($doc, $update);
            $db_conn->commit();
            $data_insert->append($doc['id']);
        } catch (Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
            $db_conn->rollBack();
        }
        $db_conn->beginTransaction();
        $schema->refreshHistory($doc);
        $db_conn->commit();
    }
} catch (\Exception $e) {
    $db_conn->rollBack();
    if ($iap_debug === true) {
        throw $e;
    } else {
        return_error($e);
    }
}

return_ok(['ads_data'=>$content['response'],'insert'=>$data_insert]);
