<?php

namespace lib\Services;

use lib\Core\Service as Core;

abstract class CommonService extends Core
{
    private $_model = null;
    public function __construct()
    {
        parent::__construct();
    } //
    abstract public function getModelClass(): string;
    abstract public function getEntityClass(): string;
    final public function getModel(): mixed
    {
        if ($this->_model === null) {
            $modelClass = $this->getModelClass();
            $this->_model = new $modelClass();
            // $this->_model->setDebug(true);
        }
        return $this->_model;
    }
    final public function getEntity(): mixed
    {
        $result = $this->getModel()->first();
        if (!$result) { //결과값이 없으면 null
            return $result;
        }
        $entityClass = $this->getEntityClass();
        return new $entityClass($result);
    }
    final public function getEntities(): array
    {
        $entitys = [];
        foreach ($this->getModel()->get() as $result) {
            $entityClass = $this->getEntityClass();
            $entity = new $entityClass($result);
            $pairField = $this->getModel()->getPairField();
            $entitys[$entity->$pairField] = $entity;
        }
        return $entitys;
    } // 
    final public function getCount(string $select = "COUNT(*) as cnt"): int
    {
        $count =  $this->getModel()->count($select);
        // echo "<BR>" . $this->getModel()->getLastQuery();
        return $count;
    }
} //Class
