<?php


namespace Lib\Imap\Request;

use Lib\Imap\Imap;
use Lib\Imap\ImapSearch;
use Lib\Imap\Parse\Messager;

/**
 * 登录
 * @author:dc
 * @time 2024/9/13 17:09
 * Class Login
 * @package Lib\Imap\Request
 */
class Msg extends Request{

    /**
     * @var Folder
     */
    public Folder $folder;

    /**
     * 读取列表条件
     * @var array
     */
    protected array $number = [];


    /**
     * 是否是uid
     * @var bool
     */
    private bool $isUid = false;


    public function __construct(Imap $imap, Folder $folder)
    {
        parent::__construct($imap);

        $this->folder = $folder;
    }


    public function exec(): static{return $this;}



    /**
     * 分页读取
     * @param int $p
     * @param int $limit
     * @return $this
     * @author:dc
     * @time 2024/9/14 14:06
     */
    public function forPage(int $p=1, int $limit=20):static {
        $this->msgno(range(($p-1)*$limit+1,$p*$limit));
        return $this;
    }

    /**
     * 使用uid进行查询
     * @param array $uids
     * @return $this
     * @author:dc
     * @time 2024/9/14 14:06
     */
    public function uid(array $uids):static {
        $this->isUid = true;
        $this->number =   $uids;
        return $this;
    }

    /**
     * 使用编号进行查询
     * @param array $msgno
     * @return $this
     * @author:dc
     * @time 2024/9/14 14:06
     */
    public function msgno(array $msgno):static {
        $this->isUid = false;
        $this->number =   $msgno;
        return $this;
    }

    /**
     * 搜索
     * @param ImapSearch $search
     * @return $this
     * @author:dc
     * @time 2024/9/14 15:48
     */
    public function search(ImapSearch $search):static {
        $this->folder->exec(); // 防止在其他文件夹下面
        $this->cmd("UID SEARCH ",$search->toString());
        $uids = [];
        foreach ($this->result as $item){
            // 匹配uid * SEARCH 2 84 882
            if(preg_match("/^\* SEARCH ([0-9\s]{1,})$/i",$item,$m)){
                $uids = array_merge($uids,explode(' ',$m[1]));
            }
        }
        $this->uid($uids);
        return $this;
    }


    /**
     * 读取邮件列表
     * @return Messager
     * @author:dc
     * @time 2024/9/14 15:34
     */
    public function get():Messager{
        $this->folder->exec(); // 防止在其他文件夹下面
        $this->cmd(
            "%sFETCH %s (UID FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER)",
            $this->isUid?'UID ':'',
            implode(',',$this->number)
        );

        return new Messager($this->result, $this);
    }


    public function getBody(){
        $this->folder->exec(); // 防止在其他文件夹下面
        $this->cmd(
            "%sFETCH %s (UID FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER)",
            $this->isUid?'UID ':'',
            implode(',',$this->number)
        );

        return new Messager($this->result, $this);
    }



}