<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/4/6
 * Time: 上午10:50
 */

namespace user_session;

require_once (BASE_ROOT_PATH . '/helper/algorithm.php');
require_once (BASE_ROOT_PATH . '/helper/session_helper.php');

use algorithm;
use session_helper;


class anotice
{
    private $mGoods;
    private $mDirty;

    public function __construct()
    {
        $this->mGoods = [];
        $this->mDirty = false;

        if(isset($_SESSION['arrival_notice'])) {
            $this->mGoods = $_SESSION['arrival_notice'];
        } else {
            $this->onStatus();
        }
    }
    public function __destruct()
    {
        if($this->mDirty) {
            $_SESSION['arrival_notice'] = $this->mGoods;
        }
        $this->mDirty = false;
    }

    public function onStatus()
    {
        $this->mGoods = [];
        $this->mDirty = true;

        $mod_anotice = Model('arrival_notice');
        $notices = $mod_anotice->getArrivalNoticeList(array('member_id' => $_SESSION['member_id']));

        foreach ($notices as $item)
        {
            $goods_id = intval($item['goods_id']);
            if($goods_id > 0) {
                $this->mGoods[] = $goods_id;
            }
        }
        sort($this->mGoods);
    }

    public function add($goods_id)
    {
        $goods_id = intval($goods_id);

        if(algorithm::binary_search($this->mGoods,$goods_id) == false) {
            $pos = algorithm::lower_bonud($this->mGoods,$goods_id);
            algorithm::array_insert($this->mGoods,$pos,$goods_id);
            $this->mDirty  = true;
        }
    }

    public function del($goods_id)
    {
        $goods_id = intval($goods_id);

        if(algorithm::binary_search($this->mGoods,$goods_id) == true) {
            $pos = algorithm::lower_bonud($this->mGoods,$goods_id);
            algorithm::array_erase($this->mGoods,$pos);
            $this->mDirty  = true;
        }
    }

    public function noticed($goods_id)
    {
        if(!session_helper::logined()) return false;

        $goods_id = intval($goods_id);
        return algorithm::binary_search($this->mGoods,$goods_id);
    }
}