<?php

namespace App\Controllers\CLI\DBMigration;

use CodeIgniter\Database\BaseConnection;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\DBMigration\Process\ClientProcess;
use App\Libraries\DBMigration\Process\LineProcess;
use App\Libraries\DBMigration\Process\ServerCodeProcess;
use App\Libraries\DBMigration\Process\SWITCHCodeProcess;
use App\Libraries\DBMigration\Process\PartCodeProcess;

class SourceDB extends DBMigration
{
    private $_sourceDB = null;

    /**
     * SQL 쿼리 상수 정의
     */
    private const SQL_GET_CLIENT = "SELECT * FROM clientdb";
    private const SQL_GET_LINE = "SELECT Line_code, line_case, Line_ip, line_client_name, line_gateway, line_id, line_pass, line_name, line_haveip, line_phone, line_mainip FROM linedb";
    private const SQL_GET_SERVER_CODE = "SELECT DISTINCT(server_code) FROM serverdb WHERE server_code NOT LIKE ?";
    private const SQL_GET_SWITCH_CODE = "SELECT DISTINCT(service_sw) FROM servicedb WHERE service_sw NOT LIKE ?";

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
    }

    /**
     * 소스 데이터베이스 연결 반환
     */
    final protected function getSourceDB(): BaseConnection
    {
        if ($this->_sourceDB === null) {
            $config = [
                'DSN'      => '',
                'hostname' => env('database.source.hostname', 'localhost'),
                'username' => env('database.source.username', 'root'),
                'password' => env('database.source.password', ''),
                'database' => env('database.source.database', 'primeidc'),
                'DBDriver' => 'MySQLi',
                'DBPrefix' => '',
                'pConnect' => false,
                'DBDebug'  => (ENVIRONMENT !== 'production'),
                'cacheOn'  => false,
                'cacheDir' => '',
                'charset'  => 'utf8mb4',
                'DBCollat' => 'utf8mb4_general_ci',
                'swapPre'  => '',
                'encrypt'  => false,
                'compress' => false,
                'strictOn' => false,
                'failover' => [],
                'port'     => 3306,
            ];
            $this->_sourceDB = \Config\Database::connect($config);
        }
        return $this->_sourceDB;
    }

    /**
     * 공통 쿼리 실행 메서드
     */
    private function executeQuery(string $sql, array $params = []): array
    {
        return $this->getSourceDB()
            ->query($sql, $params)
            ->getResultArray();
    }
    private function executeFile(string $filename, string $deilmeter = ','): array
    {
        $datas = [];
        $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $datas[] = explode($deilmeter, $line);
        }
        return $datas;
    }

    protected function getClient(): array
    {
        return $this->executeQuery(self::SQL_GET_CLIENT);
    }

    protected function getLine(): array
    {
        return $this->executeQuery(self::SQL_GET_LINE);
    }

    protected function getServerCode(): array
    {
        return $this->executeQuery(self::SQL_GET_SERVER_CODE, ['%일회성%']);
    }

    protected function getSWITCHCode(): array
    {
        return $this->executeQuery(self::SQL_GET_SWITCH_CODE, ['%일회성%']);
    }
    protected function getPartCode(): array
    {
        return $this->executeFile('/home/donfig/dbmsv2/app/Database/dbmsv2_part.txt');
    }
    final public function client(): void
    {
        $this->migration(
            new ClientProcess($this->getTargetDB()),
            $this->getClient(),
            __FUNCTION__
        );
    }

    final public function line(): void
    {
        $this->migration(
            new LineProcess($this->getTargetDB()),
            $this->getLine(),
            __FUNCTION__
        );
    }

    final public function servercode(): void
    {
        $this->migration(
            new ServerCodeProcess($this->getTargetDB()),
            $this->getServerCode(),
            __FUNCTION__
        );
    }

    final public function switchcode(): void
    {
        $this->migration(
            new SWITCHCodeProcess($this->getTargetDB()),
            $this->getSWITCHCode(),
            __FUNCTION__
        );
    }
    final public function partcode(): void
    {
        $this->migration(
            new PartCodeProcess($this->getTargetDB()),
            $this->getPartCode(),
            __FUNCTION__
        );
    }
}
