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

namespace activity;

require_once (BASE_ROOT_PATH . '/helper/message/msgutil.php');

use StatesHelper;
use Log;
use special_manager;
use algorithm;
use commonid_helper;

class goods_sampler
{
    public static $stInstance;

    private $mMaleGoods;
    private $mFemaleGoods;

    private function __construct()
    {
        $this->mFemaleGoods = [];
        $this->mMaleGoods = [];
    }

    static public function instance()
    {
        if(self::$stInstance == null) {
            self::$stInstance = new goods_sampler();
        }
        if(StatesHelper::fetch_state('goods_sampler'))
        {
            Log::record("goods_sampler reinit data.",Log::DEBUG);
            self::$stInstance->init();
        }
        return self::$stInstance;
    }

    public function fetch_male($count)
    {
        return $this->fetch($this->mMaleGoods,$count);
    }
    public function fetch_female($count)
    {
        return $this->fetch($this->mFemaleGoods,$count);
    }

    private function fetch(array $datas,$count)
    {
        $total = count($datas);
        if($total <=0 || $total < $count) return [];

        $poses = [];
        for ($i = 0; $i < $count;)
        {
            $pos = mt_rand(0,$total - 1);
            if(algorithm::binary_search($poses,$pos) == false) {
                $cur_pos = algorithm::lower_bonud($poses,$pos);
                algorithm::array_insert($poses,$cur_pos,$pos);
                $i++;
            }
        }

        $result = [];
        foreach ($poses as $pos) {
            $gid = $datas[$pos];
            $cid = commonid_helper::instance()->common_id($gid);
            if($cid != false) {
                $result[] = $cid;
            }
        }

        return $result;
    }


    private function read($spid)
    {
        $spid = intval($spid);
        if($spid <= 0) return [];

        special_manager::instance()->special($spid,$goods_ids);
        if(empty($goods_ids)) {
            return [];
        } else {
            return $goods_ids;
        }
    }

    private function init()
    {
        global $config;
        $sp_male = $config['goods_sampler']['male'];
        $sp_female = $config['goods_sampler']['female'];
        $this->mMaleGoods = $this->read($sp_male);
        $this->mFemaleGoods = $this->read($sp_female);
    }
}