<?php
namespace Bitrix\Main\IO;

class File
	extends FileEntry
	implements IFileStream
{
	public function __construct($path)
	{
		parent::__construct($path);
	}

	public function Open($mode)
	{
		$fd = fopen($this->GetPhysicalPath(), $mode."b");
		if (!$fd)
			throw new FileOpenException($this->originalPath);

		return $fd;
	}

	public function IsExists()
	{
		$p = $this->GetPhysicalPath();
		return file_exists($p) && is_file($p);
	}

	public function GetContents()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return file_get_contents($this->GetPhysicalPath());
	}

	public function PutContents($data)
	{
		$dir = $this->GetDirectory();
		if (!$dir->IsExists())
			$dir->Create();

		if ($this->IsExists() && !$this->IsWritable())
			$this->MarkWritable();

		return file_put_contents($this->GetPhysicalPath(), $data);
	}

	public function GetFileSize()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return intval(filesize($this->GetPhysicalPath()));
	}

	public function IsWritable()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return is_writable($this->GetPhysicalPath());
	}

	public function IsReadable()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return is_readable($this->GetPhysicalPath());
	}

	public function ReadFile()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return readfile($this->GetPhysicalPath());
	}

	public function GetCreationTime()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return filectime($this->GetPhysicalPath());
	}

	public function GetLastAccessTime()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return fileatime($this->GetPhysicalPath());
	}

	public function GetModificationTime()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return filemtime($this->GetPhysicalPath());
	}

	public function MarkWritable()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		@chmod($this->GetPhysicalPath(), BX_FILE_PERMISSIONS);
	}

	public function GetPermissions()
	{
		if (!$this->IsExists())
			throw new FileNotFoundException($this->originalPath);

		return fileperms($this->GetPhysicalPath());
	}

	public function Delete()
	{
		if ($this->IsExists())
			return unlink($this->GetPhysicalPath());

		return true;
	}

	public static function IsFileExists($path)
	{
		$f = new self($path);
		return $f->IsExists();
	}

	public static function GetFileContents($path)
	{
		$f = new self($path);
		return $f->GetContents();
	}

	public static function PutFileContents($path, $data)
	{
		$f = new self($path);
		return $f->PutContents($data);
	}

	public static function DeleteFile($path)
	{
		$f = new self($path);
		$f->Delete();
	}
}
