<?php

namespace plugins\buena\src\Pfadfinden\WordPress;

use Pfadfinden\WordPress\wordpress;
use plugins\buena\src\Pfadfinden\WordPress\BuenaSettings;
use plugins\buena\src\Pfadfinden\WordPress\BuenaSettingsPage;
use wordpress\src\Shy\WordPress\Theme;



class BuenaTheme extends wordpress\src\Shy\WordPress\Theme
{
	/**
	 * @var BuenaSettings
	 */
	protected $settings;


	public function getContentWidth()
	{
		return 684;
	}

	public function __construct()
	{
		parent::__construct();

		$this->settings = new BuenaSettings();

		$this->addHookMethod( 'after_setup_theme', 'afterSetupTheme' );
		$this->addHookMethod( 'wp_enqueue_scripts', 'enqueueScriptsStyles' );

		$this->addHookMethod( 'buena_search_form', 'printSearchForm' );

		$this->addHookMethod( 'admin_init', 'initAdministration' );
		$this->addHookMethod( 'mce_css', 'filterEditorStylesheets' );

		$this->addHookMethod( 'wp_page_menu', 'filterPageMenu' );
		$this->addHookMethod( 'widgets_init', 'registerSidebars' );

		$this->addHookMethod( 'the_content', 'filterContent' );

		$this->addHookMethod( 'image_size_names_choose', 'filterImageSizeNames' );
		$this->addHookMethod( 'media_upload_tabs', 'filterMediaTabs' );
		$this->addHookMethod( 'media_view_settings', 'filterMediaViewSettings' );
		$this->addHookMethod( 'media_view_strings', 'filterMediaViewSettings' );
		$this->addHookMethod( 'print_media_templates', 'printMediaTemplates' );
	}


	public function afterSetupTheme()
	{
		add_theme_support( 'title-tag' );
		add_theme_support( 'automatic-feed-links' );

		register_nav_menu( 'primary', __( 'Hauptmenü', 'buena-theme' ) );
		register_nav_menu( 'footer',  __( 'Fußzeile',  'buena-theme' ) );

		add_theme_support( 'html5', [
			'comment-list', 'comment-form', 'search-form', 'gallery', 'caption',
		] );

		add_theme_support( 'post-thumbnails' );
		$custom_header = [
			'width'         => apply_filters( 'buena_header_image_width', 1300 ),
			'height'        => apply_filters( 'buena_header_image_height', 635 ),
			'flex-width'    => true,
			'flex-height'   => true,
			'default-image' => get_template_directory_uri() . '/img/leitbild_aktionen_low.jpg',
			'uploads'       => true,
			'header-text'   => false,
		];
		add_theme_support( 'custom-header', $custom_header );
		set_post_thumbnail_size( $custom_header['width'], $custom_header['height'], true );

		add_image_size( 'gallery-thumb', 350, 165, true );

		register_default_headers( [
			'aktionen' => [
				'url'           => '%s/img/leitbild_aktionen_low.jpg',
				'thumbnail_url' => '%s/img/leitbild_aktionen_low_klein.jpg',
				'description'   => __( 'Leitbild Aktionen', 'buena-theme' ),
			],
			'bund' => [
				'url'           => '%s/img/leitbild_bund_crop.jpg',
				'thumbnail_url' => '%s/img/leitbild_bund_crop_klein.jpg',
				'description'   => __( 'Leitbild Bund', 'buena-theme' ),
			],
			'ihs' => [
				'url'           => '%s/img/leitbild_ihs.jpg',
				'thumbnail_url' => '%s/img/leitbild_ihs_klein.jpg',
				'description'   => __( 'Leitbild Immenhausen', 'buena-theme' ),
			],
			'international' => [
				'url'           => '%s/img/leitbild_int2_low.jpg',
				'thumbnail_url' => '%s/img/leitbild_int2_low_klein.jpg',
				'description'   => __( 'Leitbild International', 'buena-theme' ),
			],
			'kontakt' => [
				'url'           => '%s/img/leitbild_Kontakt_low.jpg',
				'thumbnail_url' => '%s/img/leitbild_Kontakt_low_klein.jpg',
				'description'   => __( 'Leitbild Kontakt', 'buena-theme' ),
			],
			'pfadfinden' => [
				'url'           => '%s/img/leitbild_pfadfinden_low.jpg',
				'thumbnail_url' => '%s/img/leitbild_pfadfinden_low_klein.jpg',
				'description'   => __( 'Leitbild Pfadfinden', 'buena-theme' ),
			],
		] );
	}

	public function getTeaserImage()
	{
		if ( is_page() || have_posts() && is_single() ) { // FIXME: is_singular()?
			the_post();
			$thumb = get_the_post_thumbnail( null, 'post-thumbnail', [ 'alt' => '' ] );
			rewind_posts();

			if ( $thumb ) {
				return $thumb;
			}
		}

		if ( is_home() || $this->settings['always_show_poster'] ) {
			return sprintf(
				'<img src="%s" height="%d" width="%d" alt="" />',
				get_header_image(),
				get_custom_header()->height,
				get_custom_header()->width
			);
		}

		return '';
	}

	/**
	 * Gibt einen Titel für die aktuelle Seite aus.
	 */
	public function printTitle()
	{
		if ( is_singular() ) {
			the_title();
		} elseif ( is_category() && strpos( $_SERVER['HTTP_HOST'], 'abendlager.pfadfinden.de' ) !== false ) {
			// FIXME: Workaround mit 1.0 entfernen.
			single_cat_title( '', true );
		} elseif ( is_archive() ) {
			the_archive_title();
		} elseif ( is_search() ) {
			esc_html_e( sprintf(
				__( 'Suche nach „%s“', 'buena-theme' ),
				get_search_query( false )
			) );
		} else {
			bloginfo( 'description' );
		}
	}

	public function enqueueScriptsStyles()
	{
		wp_enqueue_style( 'immenhausen-font', get_template_directory_uri() . '/font/ihs.css' );
		wp_enqueue_style( 'buena-style', get_stylesheet_uri() );
	}

	/**
	 * Gibt das Suchformular aus. Nötig, damit im Kopf anderer Code stehen kann als anderswo.
	 */
	public function printSearchForm()
	{
		get_search_form( true );
	}

	/**
	 * Tut, was dransteht.
	 */
	public function registerSidebars()
	{
		register_sidebar( [
			'id'           => 'below-navigation',
			'name'         => __( 'Unter Navigation', 'buena-theme' ),
			'description'  => __( 'Ziemlich schmal.', 'buena-theme' ),
			'before_title' => '<h4 class="h-widget">',
			'after_title'  => '</h4>',
		] );
		register_sidebar( [
			'id'          => 'footer',
			'name'        => __( 'Fußleiste', 'buena-theme' ),
			'description' => __( 'Rechte Spalte des Briefumschlags. Recht flach. Füllt die ganze Breite aus, wenn kein Navigationsmenü zugewiesen ist.', 'buena-theme' ),
			'before_title' => '<h4 class="h-widget">',
			'after_title'  => '</h4>',
		] );
	}

	/**
	 * Ausgabe von wp_page_menu() filtern, dass sie wie wp_nav_menu() aussieht.
	 * 
	 * @param string $menu
	 * @param array  $args
	 * @return string
	 */
	public function filterPageMenu( $menu, array $args )
	{
		if ( ! isset( $args['fallback_cb'] ) || $args['fallback_cb'] !== 'wp_page_menu' ) {
			return $menu;
		}

		$vorher = '<div class="' . esc_attr( $args['menu_class'] ) . '">';

		$danach = '<' . $args['container'];
		if ( $args['container_class'] ) {
			// In diesem Fall doch optional…
			$danach .= ' class="' . esc_attr( $args['container_class'] ) . '"';
		}
		if ( $args['container_id'] ) {
			$danach .= ' id="' . esc_attr( $args['container_id'] ) . '"';
		}
		$danach .= '>';

		if ( strpos( $menu, '<ul>' ) !== false ) {
			// Wenn das Menü leer ist, enthält es den <ul>-Teil nicht.
			$vorher .= '<ul>';
			$danach .= '<ul class="' . esc_attr( $args['menu_class'] ) . '">';
		}

		$menu = str_replace( $vorher, $danach, $menu );
		$menu = substr( $menu, 0, -5 ) . $args['container'] . ">\n";

		$menu = str_replace( "class='children'", 'class="sub-menu"', $menu );
		$menu = str_replace( 'current_page_item', 'current_page_item current-menu-item', $menu );
		$menu = str_replace( 'current_page_ancestor', 'current_page_ancestor current-menu-ancestor', $menu );

		return $menu;
	}

	/**
	 * Zusatzfunktionen für das Backend laden.
	 */
	public function initAdministration()
	{
		if ( isset( $_GET['exp'] ) && class_exists( 'plugins\buena\src\Pfadfinden\WordPress\BuenaSettingsPage' ) ) {
			new BuenaSettingsPage( $this->settings );
		}

		add_editor_style();
	}

	/**
	 * Standard-Skin des Editors rauswerfen.
	 * 
	 * @param string $stylesheets
	 * @return string
	 */
	public function filterEditorStylesheets( $stylesheets )
	{
		$stylesheets = explode( ',', $stylesheets );
		$stylesheets = array_filter( $stylesheets, function ( $url ) {
			return strpos( $url, 'tinymce' ) === false;
		} );

		return implode( ',', $stylesheets );
	}

	/**
	 * Überschriften <h1> und <h2> durch <h3> ersetzen.
	 * 
	 * @param string $content
	 * @return string
	 */
	public function filterContent( $content )
	{
		$content = preg_replace( '/\\<h[12]([^>]*)>(.*?)\\<\\/h[12]>/', '<h3$1>$2</h3>', $content );

		return $content;
	}

	/**
	 * @param array $names
	 * @return array
	 */
	public function filterImageSizeNames( array $names )
	{
		return $names;
	}

	/**
	 * @param array $tabs
	 * @return array
	 */
	public function filterMediaTabs( $tabs )
	{
		return $tabs;
		return $tabs + [
			'insert-poster' => __( 'Posterbilder', 'buena-theme' ),
		];
		// Erzeugt einen <iframe> von wp-admin/media-upload.php?chromeless=1&post_id=123456&tab=insert-poster
	}

	public function filterMediaViewSettings( $settings )
	{
		//var_dump( $settings );
		return $settings;
	}

	/**
	 * Weitere Templates für Medienbrowser ausgeben.
	 */
	public function printMediaTemplates()
	{
		global $_wp_default_headers;
		?>
		<script type="text/html" id="tmpl-insert-poster">
			<ul>
			<?php foreach ( $_wp_default_headers as $k => $header ) : ?>
				<img alt="<?php esc_attr_e( $header['description'] ); ?>" src="<?php echo esc_url( sprintf( $header['thumbnail_url'], get_template_directory_uri() ) ); ?>" />
			<?php endforeach; ?>
			</ul>
		</script>
		<?php
	}
}
