<?php
namespace Manage\Src;

use Dever;

class Filter
{
    /**
     * tool 过滤工具包，可以同时有多个过滤工具包，如保10洁等，系统自带了一个自定义的过滤工具
     *
     * @var array
     */
    private $tool = array();

    /**
     * setTool
     *
     * @return mixed
     */
    public function setTool($tool)
    {
        $this->tool = $tool;
    }

    /**
     * init
     *
     * @return mixed
     */
    private function init()
    {
        if (!$this->tool) {
            $this->tool = Dever::config('base')->filter ? Dever::config('base')->filter : false;
        }
    }

    /**
     * __call
     *
     * @return mixed
     */
    public function handle($param)
    {
        $this->init();

        $table_id = $param[2]['project'] . '.' . $param[2]['table'] . '.' . $param[0];

        $content = base64_encode(json_encode($param));
        Dever::load('manage/filter_task-insert', array('add_name' => $table_id, 'add_content' => $content));
    }

    /**
     * cron
     *
     * @return mixed
     */
    public function cron()
    {
        $this->init();

        if (!$this->tool) {
            return;
        }

        $data = Dever::load('manage/filter_task-data');

        if ($data) {
            $keys = implode(',', array_keys($data));
            Dever::load('manage/filter_task-dels', $keys);

            foreach ($this->tool as $k => $v) {
                $class = 'DeverApp\\Manage\\Filter\\' . $k;
                foreach ($data as $i => $j) {
                    list($project, $table, $id) = explode('.', $j['name']);
                    $content = json_decode(base64_decode($j['content']));
                    $class::cron($v, $content[1], $project, $table, $id, $j['name']);
                }
            }
        }
    }

    /**
     * callback
     *
     * @return mixed
     */
    public function callback()
    {
        $this->init();

        if (!$this->tool) {
            return;
        }

        foreach ($this->tool as $k => $v) {
            $class = 'DeverApp\\Manage\\Filter\\' . $k;
            $class::callback($v);
        }
    }
}
