<?php

namespace Velis\Mail\Storage;

use Zend\Mail\Storage\Maildir as ZendMaildir;
use Zend\Mail\Storage\Message\File;

/**
 * Maildir extension that read files in alphabetical order
 * @author Olek Procki <olo@velis.pl>
 */
class Maildir extends ZendMaildir
{
    public function __construct($params)
    {
        parent::__construct($params);

        // in case of newer versions, override the default value of messageClass property
        if (method_exists(get_parent_class($this), 'getMaildirFiles')) {
            $this->messageClass = File::class;
        }
    }


    /**
     * Find all files in opened dir handle and add to maildir files
     *
     * @param resource $dh            dir handle used for search
     * @param string   $dirname       dirname of dir in $dh
     * @param array    $defaultFlags default flags for given dir
     */
    protected function getMaildirFiles($dh, $dirname, $defaultFlags = array())
    {
        // two lines of code below should be removed when lib/Velis will completely depend on up-to-date Zend\Mail versions
        $methodName = method_exists(get_parent_class($this), 'getMaildirFiles') ? 'getMaildirFiles' : '_getMaildirFiles';
        call_user_func([$this, 'parent::' . $methodName], $dh, $dirname, $defaultFlags);

        $sortFiles = array();
        foreach ($this->files as $file) {
            $sortFiles[$file['filename']] = $file;
        }
        ksort($sortFiles);
        $this->files = array_values($sortFiles);
    }


    /**
     * @deprecated Older versions of Zend\Mail component contain Maildir class with _getMaildirFiles() method, while
     * in newer versions it was renamed to getMaildirFiles().
     * @param resource $dh            dir handle used for search
     * @param string   $dirname       dirname of dir in $dh
     * @param array    $defaultFlags default flags for given dir
     */
    protected function _getMaildirFiles($dh, $dirname, $defaultFlags = array())
    {
        $this->getMaildirFiles($dh, $dirname, $defaultFlags);
    }


    /**
     * Files mail file new lines from unix to windows (required by Zend\Mail)
     * @param string $filename
     */
    public static function fixNewLines($filename)
    {
        $filename = MAIL_DIR . '/new/' . $filename;
        file_put_contents(
            $filename,
            implode("\n", explode("\r\n", file_get_contents($filename)))
        );

        file_put_contents(
            $filename,
            implode("\r\n", explode("\n", file_get_contents($filename)))
        );
    }
}
