<?php

class FlashMessage
{
  const TYPE_FILE = 'file';
  const TYPE_SESSION = 'session';

  const LEVEL_SUCCESS = 'success';
  const LEVEL_NOTICE = 'notice';
  const LEVEL_ERROR = 'error';

  const TARGET_USER = 'user';
  const TARGET_REMOTE_HOST = 'ip';
  const TARGET_BROADCAST = 'global';

  public $id;
  public $timestamp;
  public $type;
  public $level;
  public $content;
  public $permanent;
  public $target;
  public $custom_target;
  public $filename;

  /**
   * Builds a standard flash session success message
   */
  public function __construct()
  {
    $this->id = md5(rand_str("abcdef0987654321", 32));
    $this->timestamp = new DateTimeEx();
    $this->content = "";
    $this->permanent = false;
    $this->type = self::TYPE_SESSION;
    $this->level = self::LEVEL_SUCCESS;
    $this->target = self::TARGET_USER;
    $this->custom_target = null;
    $this->filename = null;
  }

  /**
   *
   * @return string
   */
  public function serialize()
  {
    return serialize($this);
  }

  /**
   *
   * @return string
   */
  public function __toString()
  {
    return $this->content;
  }

  public function getTarget()
  {
    $target = null;
    if(isEmpty($this->custom_target))
    {
      switch($this->target)
      {
        case self::TARGET_USER:
          $target = 'user_'.user()->id;
          break;
        case self::TARGET_REMOTE_HOST:
          $target = 'ip_'.$_SERVER['REMOTE_ADDR'];
          break;
        case self::TARGET_BROADCAST:
          $target = 'global';
          break;
      }
    }
    else
    {
      $target = $this->custom_target;
    }
    return $target;
  }

  /**
   *
   * @param string $path
   * @return FlashMessage
   */
  
  public static function deserializeFile($path)
  {
  	$flash = self::deserialize(file_get_contents($path));
  	$flash->filename = $path;
  	return $flash;
  }
  /**
   *
   * @param string $data
   * @return FlashMessage
   */
  public static function deserialize($data)
  {
    return unserialize($data);
  }
}
