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

namespace async;
use member_info;
use Sms;
use push_helper;
use schema_helper;
use push_sender;
use Log;
use Exception;

class sender
{
    private $mSmsFilters;
    private $mSmsParams;
    private $mSmsType;
    private $mSmsObject;


    public function __construct($sms_filters,$sends_params)
    {
        $this->mSmsFilters = $sms_filters;
        $this->mSmsFilters[] = new notapp_filter();

        $this->mSmsParams = $sends_params['sms_params'];
        $this->mSmsType = $sends_params['type'];
        $this->mSmsObject = new Sms();
    }

    public function run($minfos,$oper_result)
    {
        $params = params_table::instance()->find_params($this->mSmsType);
        foreach ($minfos as $minfo)
        {
            try
            {
                if($this->filtrate($minfo)) {
                    Log::record("send_sms",Log::DEBUG);
                    $this->send_sms($minfo);
                }
                else {
                    Log::record("send_push",Log::DEBUG);
                    $this->send_push($minfo,$params,$oper_result);
                }
                usleep(100000);
            }
            catch (Exception $ex)
            {
                Log::record(__METHOD__ . " {$ex->getTraceAsString()}",Log::ERR);
            }
        }
    }

    private function send_sms(member_info $minfo)
    {
        $mobile = $minfo->mobile();
        $status = $this->mSmsObject->send_oper($mobile,$this->mSmsType,$this->mSmsParams);
        return ($status == 0);
    }

    private function schema_url($oper_result)
    {
        if(empty($oper_result)) return '';
        if(array_key_exists('type_sn',$oper_result)) {
            $type_sn = $oper_result['type_sn'];
            return schema_helper::bonus_detail($type_sn);
        }
        else {
            return '';
        }
    }

    private function send_push($minfo,$params,$oper_result)
    {
        $title = $params['push_title'];
        $text  = $params['push_text'];
        $url = $this->schema_url($oper_result);

        $user = $minfo->member_id();
        $push_param = push_helper::pop_message($user,$title,$text,$url);
        $push = new push_sender();
        $status = $push->send($push_param);
    }

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

        return true;
    }

    public static function create($sms_filters,$sms_params)
    {
        return new sender($sms_filters,$sms_params);
    }
}