<?php

require_once './vendor/autoload.php';

require_once 'sparql/sparql.php';
require_once 'templates/templates.php';

const OUTPUT_DIR = 'website/node/';
const NODES_DB   = "website/nodes.sqlite";

$nodes_offset = 0;

// Create SQLite database for nodes
is_file (NODES_DB) && unlink (NODES_DB);

// Used for searching topics
$nodes_db = new PDO ('sqlite:' . NODES_DB);

// https://secure.php.net/manual/it/pdo.setattribute.php
$nodes_db->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Create SQLite table
$nodes_db->exec (
    'CREATE TABLE IF NOT EXISTS `node` (' .
        '`uri` TEXT NOT NULL UNIQUE,' .
        '`name` TEXT NOT NULL,' .
        '`disambiguatingDescription` TEXT NOT NULL,' .
        '`description` TEXT NOT NULL,' .
        'PRIMARY KEY(`uri`))');

// Use a transaction to insert nodes in bunch, because 1-by-1 is too slow.
$nodes_db->beginTransaction ();
$ist = $nodes_db->prepare ('INSERT INTO `node` (`uri`, `name`, `disambiguatingDescription`, `description`) VALUES (?,?,?,?)');

while (True)
{
    // Get next node to evaluate, starting from $offset=0
    $a_uri = sparql\next_node ($nodes_offset);
    
    // Move offset forward to select next node
    $nodes_offset += 1;
    
    // No more nodes found? Job finished!
    if (count ($a_uri['results']['bindings']) == 0)
    {
        // Commit last open transaction with remaining nodes
        $nodes_db->commit ();
        break;
    }
    
    // Extract the URI value from the previous JSON result
    $uri = $a_uri['results']['bindings'][0]['subject']['value'];
    
    // Tag this node (tags are used to decide which properties to output)
    $tags = sparql\tag_node ($uri);
    
    // Build the DOKK node
    $node = sparql\dokk_node ($uri, $tags);
    
    if (is_null ($node))
        continue;
    
    // Make HTML page for this node
    $node_html = templates\render_html ($node, $uri, $tags);
    
    // Where do we store the page?
    echo $node['dokk:uri'] . "\n";
    $file_name = sha1 ($node['dokk:uri']);
    $file_path = OUTPUT_DIR . substr ($file_name, 0, 2) . '/';
    
    // Write page to file
    is_dir ($file_path) || mkdir ($file_path, 0755, TRUE);
    file_put_contents ($file_path . $file_name, $node_html);
    
    // Add node to SQLite. This database is only used to search topics
    $ist->execute ([
        $node['dokk:uri'],
        $node['schema:name'],
        $node['schema:disambiguatingDescription'],
        $node['schema:description']
    ]);
    
    // Commit SQLite transaction every few items (fewer items is slower)
    if ($nodes_offset % 200 == 0)
    {
        $nodes_db->commit ();
        $nodes_db->beginTransaction ();
        
        break;
    }
}






