<?php
/**
 * COmanage Match Database Trait
 *
 * Portions licensed to the University Corporation for Advanced Internet
 * Development, Inc. ("UCAID") under one or more contributor license agreements.
 * See the NOTICE file distributed with this work for additional information
 * regarding copyright ownership.
 *
 * UCAID licenses this file to you under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @link          https://www.internet2.edu/comanage COmanage Project
 * @package       match
 * @since         COmanage Match v1.1.0
 * @license       Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 */

declare(strict_types = 1);

namespace App\Lib\Traits;

use Cake\Datasource\ConnectionManager;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\DriverManager;

trait DatabaseTrait {
  protected $dbcxn = null;

  /**
   * Connect to the Database.
   *
   * @since  COmanage Match v1.1.0
   * @return DBALConnection
   * @throws DBALException|Exception
   */
  
  public function connectDatabase(): DBALConnection
  {
    // Use the ConnectionManager to get the database config to pass to DBAL.
    $db = ConnectionManager::get('default');
    
    // $db is a ConnectionInterface object
    $cfg = $db->config();
    
    // We only support Postgres (at least for now)
    if($cfg['driver'] !== "Cake\Database\Driver\Postgres") {
      throw new \RuntimeException(__('match.er.db.driver' , [ $cfg['driver'] ]));
    }

    // Map CAKE DB drivers to PHP DB drivers
    $driver = [
      'Cake\Database\Driver\Postgres' => 'pdo_pgsql',
      'Cake\Database\Driver\Mysql' => 'pdo_mysql',
    ];
    
    $cfargs = [
      'dbname'   => $cfg['database'],
      'user'     => $cfg['username'],
      'password' => $cfg['password'],
      'host'     => $cfg['host'],
      'driver'   => $driver[ $cfg['driver'] ]
    ];
    
    $this->dbcxn = DriverManager::getConnection($cfargs);

    return $this->dbcxn;
  }

  /**
   * Disconnect from the Database.
   * 
   * @since  COmanage Match v1.1.0
   */

  public function disconnectDatabase() {
    // DBAL doesn't have a disconnect option
    $this->dbcxn = null;

    return;
  }
}