<?php namespace Phpcmf\Model\Wheeditor; // Wheeditor表示插件目录

class Wheeditor extends \Phpcmf\Model
{
    public function __construct() {
        parent::__construct();
    }

    // 获取字段内容
    public function get_info($name = '') {
        if($name){
            $info = $this->table('wheeditor')->where('name', $name)->getAll();
        }else{
            $data = $this->table('wheeditor')->getAll();

            $info = [];
            foreach ($data as $item) {
                $info[$item['name']] = [
                    'value' => $item['value'],
                ];
            }
        }
        return $info;
    }

    // 获取CDN数据
    // $name 表示字段名称
    public function get_cdn($name = '') {
        // CDN数据们
        $data = [
            ['name' => 'localhost', 'url' => THEME_PATH . 'wheeditor', 'cname' => '本地'],
            ['name' => 'jsdelivr', 'url' => 'https://cdn.jsdelivr.net/npm/vditor@3.11.1', 'cname' => 'jsDelivr'],
            ['name' => 'iocdn', 'url' => 'https://cdn.iocdn.cc/npm/vditor@3.11.1', 'cname' => 'ioCDN'],
            ['name' => 'unpkg', 'url' => 'https://unpkg.com/vditor@3.11.1', 'cname' => 'UNPKG'],
        ];
        
        // 没有指定名称，返回所有
        if(!$name){
            return $data;
        }

        // 返回指定名称的CDN
        foreach ($data as $i) {
            if ($i['name'] == $name) {
                return $i;
            }
        }

        return $data[0];

    }

    // 获取工具栏数据
    public function get_toolbar() {
        $info = $this->get_info('toolbar');
        if($info[0]['value']){
            return $info[0]['value'];
        }

        return 
            '"bold", "italic", "strike", "link", "|",
            "list", "ordered-list", "|",
            "quote", "code", "inline-code", "|",
            "undo", "redo", "|",
            "fullscreen"'
        ;
    }

    // 保存数据
    public function save_data($data) {

        $fields = [
            'cdn', 
            'mode', 
            'icon', 
            'lang', 
            'toolbar', 
            'outline', 
            'counter', 
            'codeBlock_lineNumber', 
            'codeBlock_theme', 
            'codeBlock_preview',
        ];

        foreach ($fields as $field) {
            $item = array(
                'name' => $field,
                'value' => $data['data'][$field],
            );

            if (\Phpcmf\Service::M()->db->table('wheeditor')->where('name', $field)->countAllResults()) {
                $rt = \Phpcmf\Service::M()->db->table('wheeditor')->where('name', $field)->update($item);
            } else {
                $rt = \Phpcmf\Service::M()->db->table('wheeditor')->insert($item);
            }

            if (!$rt) {
                return 0;
            }
            
            unset($rt);
        }

        return 1;

    }
}