<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/12/2
 * Time: 下午7:27
 */

namespace async;


use push_helper;
use order_helper;
use member_info;
use Exception;
use bonus;
use bonus_helper;
use Log;
use util;

class broadcast
{
    private $mFilters;
    private $mOperator;
    private $mSender;
    private $mSmstype;

    public function __construct($filters, operator $operator, sender $sender,$sms_type)
    {
        $this->mFilters = $filters;
        $this->mOperator = $operator;
        $this->mSender = $sender;
        $this->mSmstype = $sms_type;
    }

    public function run()
    {
        $params = params_table::instance()->find_params($this->mSmstype);
        $mod_member = Model('member');
        $i = 0;
        while (true)
        {
            $start = $i * 1000;
            $items = $mod_member->field('*')->order('member_id asc')->limit("{$start},1000")->select();
            if(empty($items)) {
                return;
            }
            $i++;

            $match_users = [];
            foreach ($items as $item)
            {
                $minfo = new member_info($item);
                if($this->filtrate($minfo)) {
                    $match_users[] = $minfo;
                }
            }
            $ret = $this->mOperator->operate($match_users,$params);
            if($ret != false) {
                $this->mSender->run($match_users,$ret);
            }
        }
    }

    private function filtrate(member_info $minfo)
    {
        foreach ($this->mFilters as $filter)
        {
            if($filter->filtrate($minfo) == false) {
                return false;
            }
        }

        return true;
    }
}