<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/6/24
 * Time: 上午11:40
 */

namespace bonus;

use algorithm;
use errcode;
use predeposit_helper;
use gain_policy;

class thief_vilator
{
    private $mFromID;
    private $mDateId;

    const prifix = 'bonus_thief';
    const min_threshold = 200;

    public function __construct($fromid)
    {
        $this->mFromID = $fromid;
        $this->mDateId = strtotime(date('Y-m-d',time()));
    }

    public function thief(&$error)
    {
        if($this->can_thief() == false) {
            $error = ['code' => errcode::ErrBonus,'msg' => '每天只能偷一次好友的红包'];
            return false;
        }

        $pred = new predeposit_helper($this->mFromID);
        $usable_amount = $pred->total_bonus();
        $cents = intval($usable_amount * 100 + 0.5);
        if($cents == 0) {
            $error = ['code' => errcode::ErrBonus,'msg' => '他比你更穷，还是选择富人下手吧～'];
            return false;
        }

        $amount = $this->calc_amount($usable_amount);
        if($amount == false) {
            $error = ['code' => errcode::ErrBonus,'msg' => '今日不能偷该用户的红包～'];
            return false;
        }
        else {
            $this->add_thief();
        }

        return $amount;
    }

    private function calc_amount($usable_amount)
    {
        $policy = new gain_policy(5, $usable_amount);
        return $policy->calculate();
    }

    private function can_thief()
    {
        if(!isset($_SESSION[self::prifix]) || !array_key_exists($this->mDateId,$_SESSION[self::prifix])) {
            $_SESSION[self::prifix] = [];
            $_SESSION[self::prifix][$this->mDateId] = [];
        }

        $fromid = $this->mFromID;
        $mids = &$_SESSION[self::prifix][$this->mDateId];
        if(algorithm::binary_search($mids,$fromid)) {
            return false;
        } else {
            return true;
        }
    }
    private function add_thief()
    {
        if(!isset($_SESSION[self::prifix]) || !array_key_exists($this->mDateId,$_SESSION[self::prifix])) {
            $_SESSION[self::prifix] = [];
            $_SESSION[self::prifix][$this->mDateId] = [];
        }

        $fromid = $this->mFromID;
        $mids = &$_SESSION[self::prifix][$this->mDateId];
        if(algorithm::binary_search($mids,$fromid) == false) {
            $pos = algorithm::lower_bonud($mids,$fromid);
            algorithm::array_insert($mids,$pos,$fromid);
        }
    }
}