<?php
/**
 * Statistic module for generic content
 *
 * $Id: View.php 2239 2017-08-24 12:14:19Z gerd $
 *
 * @author gERD Schaufelberger <gerd@php-tools.net>
 * @license PHP License
 * @package WB
 * @subpackage base
 */

WBClass::load('WBStatistic');

/**
 * Statistic module for generic content
 *
 * Simple interface to save anything related to page views / sessions
 *
 * @version 0.2.0
 * @package WB
 * @subpackage base
 */
class WBStatistic_Generic extends WBStatistic
{
    /**
     * name of page view table
     */
    const TABLE = 'genericview';

    const NAMESPACE_DEFAULT =   '-';

    private $namespace  =   '';

    /**
     * constructor
     *
     * Init user and request object.
     *
     */
    public function __construct()
    {
        parent::__construct();
        $this->namespace    =   self::NAMESPACE_DEFAULT;
    }

    /**
     * Set Namespace
     *
     * @param string $ns
     * @return WBStatistic_Generic
     */
    public function setNamespace($ns = '')
    {
        if (empty($ns)) {
            $ns =   self::NAMESPACE_DEFAULT;
        }
        $this->namespace    =   $ns;
        return $this;
    }

    /**
     * Add Path to Generic Views
     *
     * Save one or more path. A path can be any string that might be useful in
     * relation with namespace
     *
     * @param string|array $path
     */
    public function add($path)
    {
        if (!$this->enabled) {
            return;
        }

        if (empty($path)) {
            return;
        }

        if (!is_array($path)) {
            $path   =   array($path);
        }

        $proto  =   array(
                        'trackid'       =>  $this->getTrackingId(),
                        'path'          =>  '',
                        'namespace'     =>  $this->namespace,
                        $this->uPrimary =>  0,
                        'counter'       =>  $this->sess->getCounter(),
                        );
        $uid    =   $this->user->getId();
        if ($uid) {
            $proto[$this->uPrimary] =   $uid;
        }

        $save   =   array();
        foreach ($path as $p) {
            $p  =   trim($p, "/ \t\n\r");
            if (empty($p)) {
                continue;
            }
            $proto['path']  =   $p;
            $save[]         =   $proto;
        }
        if (empty($save)) {
            return;
        }

        $this->table->save(self::TABLE, '__new', $save);
    }
}