<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2016/11/17
 * Time: 上午11:44
 */
namespace bonus;

class open_sharer
{
    const default_id = 1;
    private $mShareIds;
    private $mDatas;
    private static $stInstance;

    public static function instance()
    {
        if(self::$stInstance == null) {
            self::$stInstance = new open_sharer();
        }

        return self::$stInstance;
    }

    private function __construct()
    {
        $mod_share = Model('bonus_share');
        $items = $mod_share->getAll();

        $this->mShareIds = [];
        $this->mDatas = [];
        foreach ($items as $item)
        {
            $id = intval($item['share_id']);
            $val['title'] = $item['title'];
            $val['sub_title'] = $item['sub_title'];
            $val['img_url'] = BASE_SITE_URL . $item['img_url'];
            $val['share_id'] = $id;

            $this->mShareIds[] = $id;
            $this->mDatas[$id] = $val;
        }
    }

    public function get($share_id = 0)
    {
        $share_id = intval($share_id);
        if($share_id <= 0) {
            $count = count($this->mShareIds);
            $pos = mt_rand(0,$count - 1);
            $share_id = $this->mShareIds[$pos];
        }

        if(array_key_exists($share_id,$this->mDatas)) {
            return $this->mDatas[$share_id];
        }
        else {
            return $this->mDatas[self::default_id];
        }
    }
}