<?php

class VideoPressHQUploader {

	private const JS_FRONT_END_UPLOADER_KEY = 'videopress-hq-uploader-js';
	private const JS_TUS_CLIENT_KEY         = 'videopress-hq-uploader-tus-js';
	private const CSS_SCRIPT_KEY            = 'videopress-hq-uploader-style';

	const UPLOAD_METHOD_CREATE = 'create_video';
	const UPLOAD_METHOD_UPDATE = 'update_video';

	public static function render_uploader( $uploader_method ) {
		?>
		<div id='video-uploader' role="button">
			<div id='upload-prompt'>
				<div class="wp-block-button">
					<a class="wp-block-button__link wp-element-button vphq-primary-button"><?php esc_html_e( 'Select video file', 'videopress-hq' ); ?></a>
				</div>
				<?php esc_html_e( 'Or drag and drop a video file to start uploading.', 'videopress-hq' ); ?>
			</div>
			<div id='upload-error-too-many'><?php esc_html_e( 'You can only upload one video at a time', 'videopress-hq' ); ?></div>
			<div id='upload-error-not-a-video'><?php esc_html_e( 'You can only upload video files', 'videopress-hq' ); ?></div>
			<div id='upload-generic-error'></div>
			<div id='upload-progress-indicator'><div id='upload-progress-spinner'></div><div id='upload-progress-percentage'>0%</div></div>
			<input type='hidden' id='uploader_method' value='<?php echo esc_attr( $uploader_method ); ?>' />
		</div>
		<?php

		if ( self::UPLOAD_METHOD_UPDATE === $uploader_method ) {
			$post_id        = get_the_ID();
			$add_guid_nonce = wp_create_nonce( 'videopress-hq-video-add-guid-' . $post_id );
			?>
				<input type='hidden' id='add_guid_nonce' value="<?php echo $add_guid_nonce; ?>" />
			<?php
		} elseif ( self::UPLOAD_METHOD_CREATE === $uploader_method ) {
			$add_video_with_guid_nonce = wp_create_nonce( 'videopress-hq-video-add-guid-new' );
			?>
			<input type='hidden' id='add_video_with_guid_nonce' value="<?php echo $add_video_with_guid_nonce; ?>" />
			<?php
		}
	}

	// on_include
	public static function on_include() {
		global $post;

		$css_uri = get_template_directory_uri() . '/assets/css/';
		$js_uri  = get_template_directory_uri() . '/assets/js/uploader/';
		wp_register_script( self::JS_TUS_CLIENT_KEY, $js_uri . 'tus-client.js' );
		wp_register_script( self::JS_FRONT_END_UPLOADER_KEY, $js_uri . 'frontend-uploader.js', array( VideoPressHQ::GLOBAL_FUNCTIONS_SCRIPT_ID ) );

		$post_id = isset( $post->ID ) ? absint( $post->ID ) : 0;
		wp_localize_script(
			self::JS_FRONT_END_UPLOADER_KEY,
			'videopressAjax',
			array(
				'ajaxUrl' => vphq_get_admin_url( 'admin-ajax.php' ),
				'post_id' => $post_id,
			)
		);

		wp_register_style( self::CSS_SCRIPT_KEY, $css_uri . 'uploader.css' );
	}

	// on_render
	public static function on_render() {
		wp_enqueue_script( self::JS_TUS_CLIENT_KEY );
		wp_enqueue_script( self::JS_FRONT_END_UPLOADER_KEY );

		wp_enqueue_style( self::CSS_SCRIPT_KEY );
	}
}