<?php

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

namespace Tool\LoadTemplate;

class Tidy
{
    use Log;

    private ?ITidy $logic;

    private array $dbArray = array();

    /**
     * @var Save
     */
    private Save $db;

    public function __construct($db)
    {
        $this->db = $db;
    }

    public function cleanUp()
    {
        unset($this->dbArray);
        unset($this->logic);
        $this->logic = null;
        $this->dbArray = array();
    }

    public function resetLogic($logic): bool
    {
        $this->CleanUp();
        $this->logic = new $logic($this->dbArray, $this->db);
        return true;
    }

    public function dealLogic($context): bool
    {
        $this->logic->InitTplInfo();
        $this->db->InitCache($this->logic->GetTidyTableName());
        foreach ($context as $title) {
            if ($this->logic->SingleRowDeal($title) == false) {
                $log = sprintf("tidy logic[%s] deal row error", $this->logic->oldTemplateType);
                $this->addError($log);
                return false;
            }
        }
        if ($this->logic->AllTidy($context) == false) {
            $log = sprintf("tidy logic[%s] all tidy fail", $this->logic->oldTemplateType);
            $this->addError($log);
            return false;
        }
        return true;
    }

    public function save($db)
    {
        return $db->UpdateTable($this->dbArray);
    }
}
