<?php

namespace WpieFw\Files;

use WpieFw\Exceptions\WpieRuntimeException;

if( ! defined( 'ABSPATH' ) ) exit;

class WpieFile extends \SplFileInfo implements WpieFileInterface
{
	/**
	 * The files prefix
	 *
	 * @var string
	 */
	protected $prefix;

	/**
	 * Constructor
	 *
	 * @param string $filePath
	 * @param string $prefix
	 */
	public function __construct( $filePath = '', $prefix = '' )
	{
		$this->prefix = $prefix;

		parent::__construct( $filePath );
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Files\WpieFileInterface::getPrefix()
	 */
	public function getPrefix()
	{
		return $this->prefix;
	}


	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Files\WpieFileInterface::getContent()
	 */
	public function getContent()
	{
		$level = error_reporting(0);
		$content = file_get_contents( $this->getPathname() );
		error_reporting( $level );
		if ( false === $content ) {
			$error = error_get_last();
			throw new WpieRuntimeException( $error['message'] );
		}

		return $content;
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Files\WpieFileInterface::getIndex()
	 */
	public function getIndex()
	{
		if( preg_match( "/^{$this->getPrefix()}([^.]+)\\.{$this->getExtension()}$/", $this->getFilename(), $m ) ) {
			$idx = trim( $m[1] );
			return $idx;
		} else {
			throw new WpieRuntimeException( "Could not find a valid idx from file: {$this->getFilename()}" );
		}
	}
}