<?php
//define class autoloader
spl_autoload_register(function($className){
    $paths=array(
        __DIR__.'/../classes/',
        __DIR__.'/../classes/core/',
        __DIR__.'/../classes/core/exception/',
        __DIR__.'/../classes/core/authentication/',
        __DIR__.'/../classes/core/interface/',
        __DIR__.'/../classes/model/',
    );
    foreach($paths as $path){
        if(file_exists($path.$className.'.class.php')){
            include_once($path.$className.'.class.php');
        }
    }
});
    
$logLevel=Log::LOGLEVEL_DEBUG;
Log::init($logLevel, '/var/log/icebear/import.log');

Log::write(Log::LOGLEVEL_INFO, ' ');
Log::write(Log::LOGLEVEL_INFO, '=====================================');
Log::write(Log::LOGLEVEL_INFO, ' ');


Log::write(Log::LOGLEVEL_INFO,'Importer started');


Log::write(Log::LOGLEVEL_DEBUG,'Attempting to get LIMS DB connection... ');
database::connect();
Log::write(Log::LOGLEVEL_DEBUG,'...got LIMS DB connection');


database::begin();
Log::write(Log::LOGLEVEL_DEBUG,'Initializing LIMS session...');
session::init(new DummySession());
session::set('isAdmin', true);
$user=user::getByName('genericimporter');
if(empty($user)){
    Log::write(Log::LOGLEVEL_DEBUG,'Importer user does not exist, creating...');
    $user=user::create(array(
        'name'=>'genericimporter',
        'fullname'=>'Generic Importer',
        'email'=>'genericimporter@null.null',
        'password'=>'USELESSPASSWORD',
        'isactive'=>0
    ));
    $user=$user['created'];
    Log::write(Log::LOGLEVEL_DEBUG,'...created.');
} else {
    Log::write(Log::LOGLEVEL_DEBUG,'Importer user exists.');
}
session::set('userId', $user['id']);
Log::write(Log::LOGLEVEL_DEBUG,'...Initialized LIMS session.');


/* ONE-OFF score creation

$sharedProject=project::getByName(project::SHARED);
$crimsSS=crystalscoringsystem::getByName('CRIMS');
$scores=array(
	array('index'=>0, 'color'=>'7fff00', 'name'=>'Clear drop'),
	array('index'=>1, 'color'=>'0e1ef5', 'name'=>'Heavy Precipitate'),
	array('index'=>2, 'color'=>'7ab9d4', 'name'=>'Light Precipitate'),
	array('index'=>8, 'color'=>'8b4513', 'name'=>'No Diffraction'),
	array('index'=>9, 'color'=>'8b4513', 'name'=>'Low Resolution'),
	array('index'=>7, 'color'=>'8b4513', 'name'=>'Salt')
);
foreach($scores as $s){
	crystalscore::create(array(
		'projectid'=>$sharedProject['id'],
		'crystalscoringsystemid'=>$crimsSS['id'],
		'label'=>$s['name'],
		'name'=>'CRIMS_'.$s['name'],
		'color'=>$s['color'],
		'scoreindex'=>$s['index'],
		'hotkey'=>$s['index']
	));
}

*/

database::commit();


//Get the data
$json='{}';
$conf=parse_ini_file(__DIR__.'/config.ini');
if(!isset($conf['uri']) || empty($conf['uri'])){
	$json=@file_get_contents(__DIR__.'/examplePlateGroup.json');
	if(!$json){ die('Could not open example JSON file for reading'); }
} else {
	$uri=$conf['uri'];

	$username=null;
	$password=null;
	if(isset($conf['username']) && !empty($conf['username'])){ $username=$conf['username']; }
	if(isset($conf['password']) && !empty($conf['password'])){ $password=$conf['password']; }

	if(!empty($username) && !empty($password)){
		Log::write(Log::LOGLEVEL_WARN, 'Inserting username/password into URL');
		$uri=str_replace('//', '//'. $username.':'.$password.'@', $uri);
	}
	$json=file_get_contents($uri);

}

if(!$json){
	Log::write(Log::LOGLEVEL_ERROR, 'No JSON found');
	exit();
} else if('{}'==preg_replace('/\s/','',$json)){
	Log::write(Log::LOGLEVEL_INFO, 'JSON returned is empty. Nothing to do.');
	exit();
}

//Include the parser
include_once __DIR__.'/GenericImporterV0_2_0.class.php';

//Eat the data
GenericImporterV0_2_0::import($json);
