<?php


namespace CMSMSExt\FS;


class log extends File
{
  const TYPE_TXT = 'txt';
  const TYPE_CSV = 'csv';
  
  private $_types = [
    self::TYPE_TXT,
    self::TYPE_CSV
  ];
  
  private $_type = self::TYPE_TXT;
  
  public function log($messages)
  {
    $datetime    = \date_format(\date_create(), 'Y-m-d H:i:s:v');
    
    if(\is_array($messages))
    {
      $data = [];
      foreach($messages as $message)
      {
        $message = empty($message) ? '[empty message]' : $message;
        
        if($this->get_type() === self::TYPE_TXT)
        {
          $data[] = $datetime . ' :: ' . $message;
        }
        else
        {
          $data[] = '"' . $datetime . '","' . $message . '"';
        }
      }
    }
    else
    {
      $message     = empty($messages) ? '[empty message]' : $messages;
      
      if($this->get_type() === self::TYPE_TXT)
      {
        $data = $datetime . ' :: ' . $message;
      }
      else
      {
        $data = '"' . $datetime . '","' . $message . '"';
      }
    }
    
    $this->append($data)->save();
    
    return $this;
  }
  
  public function set_type(string $type)
  {
    if(!\in_array($type, $this->_types))
    {
      throw new \InvalidArgumentException('Invalid log type.');
    }
    
    $this->_type = $type;
    
    return $this;
  }
  
  public function get_type()
  {
    return $this->_type;
  }
}

?>