<?php
/**
 * Open Source Social Network
 *
 * @package   Kernel
 * @author    OpenTeknik LLC <info@openteknik.com>
 * @copyright 2020 OpenTeknik LLC
 * @license   OPENTEKNIK LLC, COMMERCIAL LICENSE v1.0
 * @link      https://www.openteknik.com/
 */
define('KERNEL', ossn_route()->com . 'Kernel/');
require_once(KERNEL . 'classes/Kernel.php');
/**
 * Show kernel related errors
 *
 * @param string $code     Error code
 * @param string $message  Message
 * 
 * @return void
 */
function ossn_kernel_error($code = '', $message = '') {
		echo ossn_plugin_view('kernel/error', array(
					'code' => $code,
					'message' => $message,											
		));
		exit;
}
/**
 * Kernel check if connection is valid
 *
 * @return boolean
 */
function ossn_kernal_is_established() {
		if(Kernel::isMemCacheStatusExpired()){
				return true;	
		}
		$kernel = new Kernel;
		$establish = $kernel->sendAuth();
		if(isset($establish) && isset($establish->data)) {
				if($establish->data == 'declined') {
						return $establish->response_code;
				}
		}
		return true;
}
/**
 * Kernel Initialize
 *
 * @return void
 */
function ossn_kernal_init() {
		ossn_add_hook('ossn', 'kernel:cred', 'ossn_kernal_auth');
		ossn_register_callback('cache', 'flushed', 'ossn_kernel_cache_flushed');
}
/**
 * Set kernal creds
 *
 * @return object|boolean
 */
function ossn_kernal_creds() {
		global $license;
		if(!is_file(KERNEL . 'license.php')) {
				return false;
		}
		include_once(KERNEL . 'license.php');
		if(isset($license['api_key'])) {
				return (object) $license;
		}
		return false;
}
/**
 * Setup a sdk for kernel
 *
 * @return void
 */
if(!Kernel::isCacheLoaded()) {
		$status = ossn_kernal_is_established();
		if($status === true){
				Kernel::setMemcachedStatus();
				Kernel::setStatus(true);
		} else {
				Kernel::setStatus(false);	
				Kernel::clearStorage();
				ossn_kernel_error($status, 'Please contact the software support team to resolve the issue!');
		}
		define('KERNEL_STATUS', $status);
} else {
		define('KERNEL_STATUS', true);
}
/**
 * Register the SDK
 *
 * @param string $type Type of SDK
 * @param string $handler Name of handler
 * 
 * @return void
 */
function ossn_register_system_sdk($type, $handler, $pcit = 4001) {
		global $Ossn;
		if(!isset($Ossn->kernelBatch)) {
				$Ossn->kernelBatch = array();
		}
		$Ossn->kernelBatch[$type] = array(
				$type,
				$handler,
				$pcit
		);
}
/**
 * Trigger the kernel
 *
 * @return void
 */
function ossn_kernel_trigger() {
		if(KERNEL_STATUS === true) {
				Kernel::setINIT();
		}
}
/**
 * Cache flush
 *
 * @return void
 */
function ossn_kernel_cache_flushed(){
		$kernel = new Kernel;
		$establish = $kernel->sendAuth();
		if(isset($establish) && isset($establish->data)){
			Kernel::clearStorage();
		}
}
ossn_register_callback('components', 'after:load', 'ossn_kernel_trigger');
ossn_register_callback('ossn', 'init', 'ossn_kernal_init');
ossn_register_system_sdk('Kernel', 'kernel_network_init');