<?php
namespace FileRun;
global $settings, $config;
if (!$config) {exit();}

if ($this->isLimitedPreview()) {
	$this->centeredThumb();
	return;
}

$fileExtension = \FM::getExtension($this->data['fileName']);

$chunkSize = Files\Actions\Upload\Utils::getUploadChunkSize();

$vars = [
	'URLRoot' => $config['url']['root'],
	'cacheid' => UI\Utils::getStaticAssetCacheID(),
	'pluginURL' => $this->url,
	'folderPath' => \FM::dirname($this->data['relativePath']),
	'filePath' => $this->data['relativePath'],
	'filePathOBJ' => \FM::replaceExtension($this->data['relativePath'], 'obj'),
	'downloadBaseURL' => $config['url']['root'].'/?module=custom_actions&action=3d_viewer&method=openInBrowser',
	'fileExtension' => $fileExtension,
	'fileNamePNG' => \FM::replaceExtension($this->data['fileName'], 'png'),
	'UploadChunkSize' => $chunkSize,
	'userCanUpload' => false,
	'windowId' => \S::fromHTML($_REQUEST['_popup_id']),
	'csrf_token' => self::getCSRFToken(),
	'devMode' => $config['dev']['mode']
];

if ($this->data['weblink']) {
	$vars['downloadBaseURL'] = $this->data['weblink']['download_url'];
	$vars['filePath'] = '';
	$vars['filePathOBJ'] = '';
	$vars['folderPath'] = '';
	if (!empty($this->data['weblink']['subPath'])) {
		$vars['filePath'] = $this->data['weblink']['subPath'];
		$vars['filePathOBJ'] = \FM::replaceExtension($this->data['weblink']['subPath'],'obj');
		$vars['folderPath'] = \FM::dirname($this->data['weblink']['subPath']);
	}
}

if (!$this->data['weblink'] && Perms::check('upload')) {
	if (!$this->data['shareInfo'] || ($this->data['shareInfo'] && $this->data['shareInfo']['perms_upload'])) {
		$vars['userCanUpload'] = true;
	}
}

if ($this->data['version']) {
	$vars['downloadBaseURL'] .= '&version='.\S::forURL($this->data['version']);
}

$requires = [
	'obj' => [
		'loaders/OBJLoader.js',
		'loaders/MTLLoader.js',
		'loaders/DDSLoader.js'
	],
	'stl' => ['loaders/STLLoader.js'],
	'fbx' => [
		'loaders/FBXLoader.js',
		'libs/inflate.min.js',
		'curves/NURBSCurve.js',
		'curves/NURBSUtils.js'
	],
	'dae' => ['loaders/ColladaLoader.js'],
	'x' => ['loaders/XLoader.js'],
	'3ds' => ['loaders/TDSLoader.js'],
	'3mf' => ['loaders/3MFLoader.js', 'libs/jszip.min.js'],
	'gltf' => [
		'loaders/GLTFLoader.js',
		'loaders/DRACOLoader.js'
	],
];
$requires['mtl'] = $requires['obj'];
$requires['glb'] = $requires['gltf'];


$page = [
	'styles' => ['basic', 'ext'],
	'scripts' => [
		'ext',
	    'flow/utils',
		$this->url.'/app.js?cache='.$vars['cacheid'],
		$this->url.'/three/three.min.js?cache='.$vars['cacheid']
	],
	'jsGlobals' => [
		'FR.vars' => $vars
	]
];

if ($requires[$fileExtension]) {
	foreach ($requires[$fileExtension] as $req) {
		$page['scripts'][] = $this->url.'/three/'.$req.'?cache='.$vars['cacheid'];
	}
}
$page['scripts'][] = $this->url.'/three/controls/OrbitControls.js?cache='.$vars['cacheid'];

require $config['path']['includes'].'/ui/page/plugin.php';