<?php
   require_once realpath(__DIR__.'/../base/constants.php');

   abstract class VideoStreamerBase {
      protected $_video_path = "";
      protected $_video_stream = null;
      protected $_require_cookie = false;

      public function __construct($video_path, $require_cookie) {
         $this->_video_path = VIDEO_DIR."/{$video_path}";
         $this->_require_cookie = $require_cookie;
      }

      public function start() {
         $this->checkCookie();
         $this->openFileStream();
         $this->setResponseHeaders();
         $this->doVideoStream();
         $this->closeFileStream();
      }

      abstract protected function setResponseHeaders();
      abstract protected function doVideoStream();

      private function checkCookie() {
         if ($this->_require_cookie) {
            $login_cookie = $_COOKIE['x-login'];
            if (!isset($login_cookie) || $login_cookie !== 'my-secret-login-cookie') {
               header("HTTP/1.1 403 Forbidden");
               exit;
            }
         }
      }

      private function openFileStream() {
         if (!($this->_video_stream = fopen($this->_video_path, 'rb'))) {
            die("Unable to open file for streaming, path={$this->_video_path}");
         }
         ob_get_clean();
      }

      private function closeFileStream() {
         if (!fclose($this->_video_stream)) {
            die("Unable to close file stream, path={$this->_video_path}");
         }
      }
   }
?>