<?php

/**
 * ITidy.php
 * 文件描述
 * Created On 2022/1/18
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Tool\LoadTemplate;

abstract class ITidy
{
    use Log;

    public int $newTemplateType;
    public int $oldTemplateType;
    public ?array $dbArray = null;
    /**
     * @var Save
     */
    private Save $db;

    public function __construct(&$context, Save $db)
    {
        $this->dbArray = &$context;
        $this->db = $db;
    }

    public function getData($tplId, $tableType): ?array
    {
        $data =  $this->db->getData($tableType, $tplId);
        if ($data == null) {
            $log = sprintf("tplName:[%s] tplId:[%d]", $tableType, $tplId);
            $this->addError($log);
            return null;
        }
        return $data;
    }

    public function setData($type, $tplId, $val): bool
    {
        return $this->db->saveData($tplId, $val, $type);
    }

    public function singleRowDeal($tpl): bool
    {
        return true;
    }

    public function allTidy($tplIdList): bool
    {
        return true;
    }

    public function getTidyTableName(): int
    {
        return $this->newTemplateType;
    }

    abstract public function initTplInfo();

    protected function addDBArray($key, $field, $value)
    {
        if (array_key_exists($key, $this->dbArray)) {
            $arr = $this->dbArray [$key];
            $arr [$field] = $value;
        } else {
            $arr = array(
                $field => $value
            );
        }
        $this->dbArray [$key] = $arr;
    }

    protected function addDBRowArray($key, $value)
    {
        $this->dbArray [$key] = $value;
    }

    protected function getDBArray($key, $field)
    {
        if (!array_key_exists($key, $this->dbArray)) {
            return null;
        }
        if (!array_key_exists($field, $this->dbArray [$key])) {
            return null;
        }
        return $this->dbArray [$key] [$field];
    }
}
