<?php

namespace idoit\Module\SyneticsJdisc\Model;

use DateTime;
use idoit\Exception\JsonException;
use idoit\Module\SyneticsJdisc\Model\Dto\LogDto;
use isys_application;
use isys_format_json;

class LogsDao extends AbstractDao
{

    /**
     * @param array|int|null $ids
     *
     * @return \isys_component_dao_result
     * @throws \isys_exception_database
     */
    public function getLogs(mixed $ids = null)
    {
        $query = "SELECT * FROM isys_jdisc_log WHERE TRUE";
        $query .= match (gettype($ids)) {
            'int' => " AND isys_jdisc_log__id = {$this->convert_sql_int($ids)}",
            'array' => " AND isys_jdisc_log__id {$this->prepare_in_condition($ids)}",
            default => ''
        };

        return $this->retrieve($query);
    }

    /**
     * @param int    $status
     * @param LogDto $dto
     *
     * @return bool
     * @throws \isys_exception_dao
     * @throws \isys_exception_database
     */
    public function save(int $status, LogDto $dto)
    {
        $db = isys_application::instance()->container->get('database');
        $profileDao = JDiscProfileDao::instance($db);
        $serverDao = JDiscServerDao::instance($db);

        $endDate = (new DateTime())->format('Y-m-d H:i:s');
        $startDate = $dto->getStartDate()->format('Y-m-d H:i:s');
        $serverId = $dto->getServerId();
        $profileId = $dto->getProfileId();
        $profileTitle = $profileDao->getProfileList($profileId)->get_row_value('isys_jdisc_profile__title');
        $serverRow = $serverDao->getServerList($serverId)->get_row();

        $profileData = isys_format_json::encode([
            'id' => $profileId,
            'title' => $profileTitle
        ]);

        $serverData = isys_format_json::encode([
            'id' => $serverId,
            'title' => $serverRow['isys_jdisc_db__title'],
            'host' => $serverRow['isys_jdisc_db__host'],
        ]);

        $saveData = [
            "isys_jdisc_log__status = {$this->convert_sql_int($status)}",
            "isys_jdisc_log__start_date = {$this->convert_sql_text($startDate)}",
            "isys_jdisc_log__end_date = {$this->convert_sql_text($endDate)}",
            "isys_jdisc_log__server_info = {$this->convert_sql_text($serverData)}",
            "isys_jdisc_log__profile_info = {$this->convert_sql_text($profileData)}",
            "isys_jdisc_log__file_name = {$this->convert_sql_text($dto->getFileName())}"
        ];

        $query = "INSERT INTO isys_jdisc_log SET " . implode(', ', $saveData);

        return $this->update($query) && $this->apply_update();
    }

    /**
     * @param string $identifier
     *
     * @return string|null
     * @throws JsonException
     */
    public static function getDownloadPath(string $identifier): ?string
    {
        $dao = isys_application::instance()->container->get('cmdb_dao');
        $id = (int)$identifier;

        $query = "SELECT isys_jdisc_log__file_name as file_name, isys_jdisc_log__server_info as server_info, isys_jdisc_log__profile_info as profile_info
            FROM isys_jdisc_log WHERE isys_jdisc_log__id = {$id};";

        $fileData = $dao->retrieve($query)->get_row();
        $serverInfo = isys_format_json::decode($fileData['server_info']);
        $profileInfo = isys_format_json::decode($fileData['profile_info']);

        $file = BASE_DIR . "/log/jdisc/{$serverInfo['id']}/{$profileInfo['id']}/{$fileData['file_name']}";
        if (!file_exists($file)) {
            return null;
        }

        return $file;
    }
}
