<?php
/*
 * PSX is an open source PHP framework to develop RESTful APIs.
 * For the current version and information visit <https://phpsx.org>
 *
 * Copyright 2010-2022 Christoph Kappestein <christoph.kappestein@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace PSX\Http\Stream;

use InvalidArgumentException;
use PSX\Http\StreamInterface;

/**
 * Stream which operates on a PHP resource
 *
 * @author  Christoph Kappestein <christoph.kappestein@gmail.com>
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @link    https://phpsx.org
 */
class Stream implements StreamInterface
{
    private mixed $resource;
    private bool $seekable = false;
    private bool $readable = false;
    private bool $writable = false;

    public function __construct($resource)
    {
        if (!is_resource($resource)) {
            throw new InvalidArgumentException('Must be an resource');
        }

        $this->setResource($resource);
    }

    public function close()
    {
        if ($this->resource) {
            fclose($this->resource);
        }

        $this->detach();
    }

    public function detach()
    {
        $handle = $this->resource;

        $this->resource = null;
        $this->seekable = $this->writable = $this->readable = false;

        return $handle;
    }

    public function getSize()
    {
        if ($this->resource) {
            $stat = fstat($this->resource);

            return $stat['size'] ?? null;
        }

        return null;
    }

    public function tell()
    {
        if ($this->resource) {
            return ftell($this->resource);
        }

        return 0;
    }

    public function eof()
    {
        if ($this->resource) {
            return feof($this->resource);
        }

        return true;
    }

    public function rewind()
    {
        if ($this->resource) {
            return rewind($this->resource);
        }

        return true;
    }

    public function isSeekable()
    {
        return $this->seekable;
    }

    public function seek($offset, $whence = SEEK_SET)
    {
        if ($this->resource && $this->seekable) {
            return fseek($this->resource, $offset, $whence);
        }

        return false;
    }

    public function isWritable()
    {
        return $this->writable;
    }

    public function write($string)
    {
        if ($this->resource && $this->writable) {
            return fwrite($this->resource, $string);
        }

        return 0;
    }

    public function isReadable()
    {
        return $this->readable;
    }

    public function read($length)
    {
        if ($this->resource && $this->readable && $length > 0) {
            return fread($this->resource, $length);
        }

        return '';
    }

    public function getContents()
    {
        if ($this->resource && $this->readable) {
            return (string) stream_get_contents($this->resource);
        }

        return '';
    }

    public function getMetadata($key = null)
    {
        if ($this->resource) {
            $meta = stream_get_meta_data($this->resource);

            if ($key === null) {
                return $meta;
            } else {
                return isset($meta[$key]) ? $meta[$key] : null;
            }
        }

        return $key === null ? array() : null;
    }

    public function __toString()
    {
        if ($this->resource && $this->readable) {
            return (string) stream_get_contents($this->resource, -1, 0);
        }

        return '';
    }

    protected function setResource($resource)
    {
        $meta = stream_get_meta_data($resource);
        $mode = $meta['mode'] . ' ';

        $this->resource = $resource;
        $this->seekable = $meta['seekable'];
        $this->writable = $mode[0] != 'r' || $mode[1] == '+';
        $this->readable = $mode[0] == 'r' || $mode[1] == '+';
    }
}
