<?php

/**
 * Created by PhpStorm.
 * User: marco
 * Date: 09/07/17
 * Time: 22.41
 */
class o66p {
	private static $greeting = 'All Hail ';
	private static $pageID = 0;
	private static $pagePostType = '';
	private static $pageTitle = '';
	private static $pageSlug = '';
	//   private static  $pageParent = '';
	//  private static  $pageHasParent = '';
	private static $pageUrl = '';
	private static $pagePostThumbnailID = 0;
	private static $isIndex = false;
	//   private static  $hasIndex = FALSE;
	//   private static  $indexObject = NULL;
	private static $initialized = false;
	private static $currentArgs = null;
	private static $optionIsIndex = array();
	private static $parentsArray = array();
	private static $sibilingsArray = array();
	private static $childrenArray = array();

	/**
	 * o66p constructor.
	 */


	private static function initialize() {
		if ( self::$initialized ) {
			return;
		}

		self::$greeting       .= ' the Dark Lord of the Twin Moons';
		self::$pageID         = get_the_ID();
		self::$pagePostType   = get_post_type( self::$pageID );
		self::$pageTitle      = get_the_title( self::$pageID );
		self::$pageSlug       = get_post_field( 'post_name', self::$pageID );
		self::$pageUrl        = get_the_permalink( self::$pageID );
		self::$pagePostThumbnailID        = get_post_thumbnail_id( self::$pageID );
		self::$isIndex        = self::checkIsIndex( self::$pageID );
		self::$optionIsIndex  = self::checkIsIndexOption( self::$pageID );
		self::$parentsArray   = self::generateParentsArray( self::$pageID );
		self::$sibilingsArray = self::generateSibilingsArray( self::$pageID );
		self::$childrenArray  = self::generateChildsArray( self::$pageID );


		self::$initialized = true;
	}


	/**
	 * @return string
	 */
	public static function getDuoToneFeaturedImage ($colorBlack = null, $colorWhite = null,  $grayscale = null,$radialValue = null, $blurValue = null, $wpSize = null, $pageID = null, $forceGeneration = null)
	{
		self::initialize();
		$grayscaleParam = '';
		$grayscaleName = 'cl';
		$blurName = 'no-blur';
		$blurParam = '';
		$radialName = 'no-radial';
		$radialParam = '';
		if (empty($pageID)) {$pageID = self::$pageID;}
		if (empty($wpSize)) {$wpSize = 'full';}
		if (empty($grayscale)) {$grayscaleParam = '';}
		if (empty($forceGeneration)) {$forceGeneration = false;}


		// http://www.imagemagick.org/Usage/blur/
		if (!empty($blurValue)) {

			$blurParam = '-blur '.$blurValue;
			$blurName = 'blur-'.$blurValue;

		}

		if (!empty($radialValue)) {
		    $radialParam = '-radial-blur '.$radialValue;
		    $radialName = 'radial-'.str_replace('.', '',$radialValue);

        }

		$imageId = get_post_thumbnail_id($pageID);
		$imageFilePathOld = get_attached_file($imageId);
		$imageFilePath = wp_get_attachment_image_src($imageId, $wpSize);


		$path = $_SERVER['DOCUMENT_ROOT'].parse_url($imageFilePath[0], PHP_URL_PATH);
 //var_dump($path);


		$background_image = $path;
		$upload_dir = wp_upload_dir();
		$base_dir = $upload_dir['basedir'] . '/o66media/';
		if(!file_exists($base_dir)) {
			mkdir($base_dir);
		}
		$imageFileName = basename(wp_get_attachment_metadata($imageId)['file']);
		if (empty($colorBlack)) {
			$colorBlack = '845ef7';
		}
		if (empty($colorWhite)) {
			$colorWhite = '748ffc';
		}

		if ($grayscale == true) {$grayscaleParam = '-colorspace Gray'; $grayscaleName = 'bw';}

		$processedImageFileName = 'duoTone-hex'.$colorBlack.'-'.$colorWhite.'-'.$grayscaleName.'-'.$radialName.'-'.$blurName.'-'.$imageId.'-'.$wpSize.'-'.$imageFileName;

		$processedImageFullFileName = $base_dir. $processedImageFileName;
	//	var_dump(basename($imageFileName['file']));

		$processedImageUrl = content_url().'/uploads/o66media/'.$processedImageFileName;

		$processedImageExists = file_exists($processedImageFullFileName);





		if ($processedImageExists == false || $forceGeneration == true) {

			//exec('/usr/bin/convert '.$background_image.' -colorspace gray -level +25% +level-colors "#44607f","#FF5533" '.$treated_image);
			//	exec('/usr/bin/convert '.$background_image.' +level-colors "#44607f","#FF5533" -blur 0x8 '.$treated_image);
			exec( '/usr/bin/convert '.$grayscaleParam.' ' . $background_image . ' +level-colors "#' . $colorBlack . '","#' . $colorWhite . '" '.$radialParam.'  '.$blurParam.'  -attenuate 0.25 +noise gaussian ' . $processedImageFullFileName );
		}

		return $processedImageUrl;



	}

	/**
	 * @return array
	 */
	public static function getChildrenArray() {
		self::initialize();
		return self::$childrenArray;
	}


	/**
	 * @return array
	 */
	public static function getParentsArray() {
		self::initialize();

		return self::$parentsArray;
	}

	/**
	 * @return array
	 */
	public static function getSibilingsArray() {
		self::initialize();

		return self::$sibilingsArray;
	}


	public static function greet() {
		self::initialize();
		echo self::$greeting;
	}

	/**
	 * @return string
	 */
	public static function getIsIndex() {
		self::initialize();

		return self::$isIndex;
	}

	/**
	 * @return string
	 */
	public static function getPageTitle() {
		self::initialize();

		return self::$pageTitle;
	}

	/**
	 * @return string
	 */
	public static function getPageUrl() {
		self::initialize();

		return self::$pageUrl;
	}

	/**
	 * @param null $currentArgs
	 */
	public static function setCurrentArgs( $currentArgs ) {
		self::initialize();
		self::$currentArgs = $currentArgs;
	}

	/**
	 * @return null
	 */
	public static function getCurrentArgs() {
		self::initialize();

		return self::$currentArgs;
	}

	/**
	 * @return array
	 */
	public static function getOptionIsIndex() {
		self::initialize();

		return self::$optionIsIndex;
	}

// noottaa

	public static function renderBlokQuery( $args, $blokSlug, $blokUniqueID = null ) {
		global $wp_query;
		self::initialize();

		$the_inc_query = new WP_Query( $args );
		$fileCore      = o66s::getSiteThemePath() . '/core/inc/inc-' . $blokSlug . '.php';
		$fileCoreItem  = o66s::getSiteThemePath() . '/core/inc/inc-' . $blokSlug . '-item.php';
		$fileLocal     = o66s::getSiteThemePath() . '/inc/inc-' . $blokSlug . '.php';
		$fileLocalItem = o66s::getSiteThemePath() . '/inc/inc-' . $blokSlug . '-item.php';

		$fileLocalExist     = file_exists( $fileLocal );
		$fileLocalItemExist = file_exists( $fileLocalItem );

		$fileCoreExist     = file_exists( $fileCore );
		$fileCoreItemExist = file_exists( $fileCoreItem );

		$blokUniqueIDCss    = '';
		$blokUniqueClassCss = '';
		//$blokUniqueClassItemCss = '';

		if ( $blokUniqueID != null ) {
			$blokUniqueIDCss    = 'id="' . $blokUniqueID . '"';
			$blokUniqueClassCss = 'blok-' . $blokSlug . '-' . $blokUniqueID;
			//$blokUniqueClassItemCss = $blokSlug.'-'.$blokUniqueID;
		}

		if ( $fileLocalExist == true ) {
			$wrapperInc = $fileLocal;
		} else {
			$wrapperInc = $fileCore;
		}

		if ( $fileLocalItemExist == true ) {
			$itemInc = $fileLocalItem;
		} else {
			$itemInc = $fileCoreItem;
		}

		//$the_query = $wp_query;

		// The Loop

		include( $wrapperInc );

		// Reset Post Data
		wp_reset_postdata();
		wp_reset_query();
		$the_inc_query = null;

	}

	private static function checkIsIndexOption( $pageID ) {//self::initialize();
		$returnIsIndex = array( false );
		$field         = get_field( 'pagine_indice', 'option' );


		if ( ! empty( $field ) ) {

			foreach ( $field as $fieldItem ) {

				if ( $pageID == $fieldItem['pagina']->ID ) {
					$returnIsIndex = array( true, $fieldItem['tipo_di_post'] );
				};
			}

		}


		return $returnIsIndex;


	}

	private static function generateParentsArray( $pageID ) {
		//	self::initialize();
		//	echo self::$greeting;
		$depth             = 0;
		$returnArray       = array( 0 );
		$parentsPostObjs   = array();
		$parentsPostIDs    = array();
		$currentPostObject = get_post( $pageID );
		$parentID          = $currentPostObject->post_parent;
		//echo 'yooo';

		//	var_dump($parentID);


		while ( $parentID > 0 ) {
			$depth ++;
			$loopParentPost = get_post( $parentID );

			array_push( $parentsPostObjs, $loopParentPost );
			array_push( $parentsPostIDs, $parentID );
			$returnArray = array( $depth, $parentsPostObjs, $parentID );


			$parentID = $loopParentPost->post_parent;


		}

		return $returnArray;


	}

	private static function generateSibilingsArray( $pageID ) {
		$sibilings        = 0;
		$returnArray      = array( 0 );
		$sibilingsArray   = array();
		$sibilingsArrayID = array();

		$currentPostObject = get_post( $pageID );
		$parentID          = $currentPostObject->post_parent;

		if ( $parentID > 0 ) {
			//echo 'yooO';
			//echo $parentID;


			$args = array(
				'post_type'   => self::$pagePostType,
				'post_parent' => $parentID
			);

			$sibilingsPosts = get_posts( $args );
			//	var_dump($sibilingsPosts);

			foreach ( $sibilingsPosts as $sibilings_post ) {
				$sibilings ++;
				array_push( $sibilingsArray, $sibilings_post );
				array_push( $sibilingsArrayID, $sibilings_post->ID );
				$returnArray = array( $sibilings, $sibilingsArray, $sibilingsArrayID );

				//var_dump($sibilings_post);
			}


		}

		return $returnArray;

	}

	private static function generateChildsArray( $pageID ) {
		$children        = 0;
		$returnArray     = array( 0 );
		$childrenArray   = array();
		$childrenArrayID = array();

		//	$currentPostObject = get_post( $pageID );
		$parentID = $pageID;

		if ( $parentID > 0 ) {
			//echo 'yooO';
			//echo $parentID;


			$args = array(
				'post_type'   => self::$pagePostType,
				'post_parent' => $parentID
			);

			$childrenPosts = get_posts( $args );
			//	var_dump($childrenPosts);

			foreach ( $childrenPosts as $children_post ) {
				$children ++;
				array_push( $childrenArray, $children_post );
				array_push( $childrenArrayID, $children_post->ID );
				$returnArray = array( $children, $childrenArray, $childrenArrayID );

				//var_dump($children_post);
			}


		}

		return $returnArray;

	}


	private static function checkIsIndex( $pageID ) {//self::initialize();
		$isIndex     = false;
		$args        = array(
			'posts_per_page'   => 1,
			'offset'           => 0,
			'category'         => '',
			'category_name'    => '',
			'orderby'          => 'date',
			'order'            => 'DESC',
			'include'          => '',
			'exclude'          => '',
			'meta_key'         => 'app_page_index',
			'meta_value'       => $pageID,
			'post_type'        => 'app_index',
			'post_mime_type'   => '',
			'post_parent'      => '',
			'author'           => '',
			'author_name'      => '',
			'post_status'      => 'publish',
			//  'name' => $appSlug,
			'suppress_filters' => true
		);
		$posts_array = get_posts( $args );
		// $posts_array = array(1,4,5);
		if ( ! empty( $posts_array ) ) {
			$isIndex = true;
		}

		return $isIndex;

	}
}