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

namespace user_session;

use algorithm;

abstract class storage
{
    const NORMAL_SUPPORT = 0;
    const DAILY_SUPPORT  = 1;

    private $mLimitType;
    private $mTag;
    private $mCurStorage; //PHP 引用不能多次传递，用类成员变量临时保存

    public function __construct()
    {
        $this->mLimitType = $this->limit_type();
        $this->mTag = $this->storage_tag();
        $this->mCurStorage = null;
    }

    public function click($uniqueid)
    {
        $uniqueid = intval($uniqueid);
        if($uniqueid < 0) {
            return false;
        }

        if($this->base_supported($uniqueid)) {
            $supported = false;
            $this->base_unsupport($uniqueid);
        } else {
            $supported = true;
            $this->base_support($uniqueid);
        }
        return $supported;
    }

    private function session_data()
    {
        if(!isset($_SESSION[$this->mTag])) {
            $_SESSION[$this->mTag] = [];
        }

        if($this->mLimitType == self::NORMAL_SUPPORT) {
            $this->mCurStorage = &$_SESSION[$this->mTag];
        }
        else
        {
            $time = strtotime(date('Y-m-d',time()));
            if(!isset($_SESSION[$this->mTag][$time])) {
                $_SESSION[$this->mTag][$time] = [];
            }
            $this->mCurStorage = &$_SESSION[$this->mTag][$time];
        }
    }

    protected function base_supported($uniqueid)
    {
        $this->session_data();
        if(algorithm::binary_search($this->mCurStorage,$uniqueid)) {
            return true;
        } else {
            return false;
        }
    }

    protected function base_support($uniqueid)
    {
        $this->session_data();
        if(algorithm::binary_search($this->mCurStorage,$uniqueid) == false) {
            $pos = algorithm::lower_bonud($this->mCurStorage,$uniqueid);
            algorithm::array_insert($this->mCurStorage,$pos,$uniqueid);
            return true;
        } else {
            return false;
        }
    }

    protected function base_unsupport($uniqueid)
    {
        $this->session_data();
        if(algorithm::binary_search($this->mCurStorage,$uniqueid) == true) {
            $pos = algorithm::lower_bonud($this->mCurStorage,$uniqueid);
            algorithm::array_erase($this->mCurStorage,$pos);
            return true;
        } else {
            return false;
        }
    }

    abstract protected function limit_type();
    abstract protected function storage_tag();
}
