<?php
/**
 * Created by Roman Liashko.
 * Date: 8/29/2016
 * Time: 3:29 PM
 *
 * How to use:
 * include this file in your script
 * connect to db: $db = CommonPDOConnector::connect('[CONNECTION_NAME]');
 */
require_once("dbConstants.php");

class CommonPDOConnector
{

    public static $error;

    private static $db = array();
    private static $dbPersistence = array();
    private static $access = array(
        'AdvertisersRead' => array(
            'host' => array("192.168.30.118", "192.168.30.119", "192.168.30.120", "192.168.30.121",
                "192.168.30.122","192.168.30.124"),
            'user' => 'c3slave',
            'pass' => 'RstG496urky2',
            'db' => 'Advertisers'
        ),
//        'ConnectToCMS' => 'cms.ini',
        'ConnectToAdmobile' => array(
            'host' => '192.168.17.110',
            'user' => 'c3slave',
            'pass' => 'RstG496u*#rky2',
            'db' => 'admobile'
        ),
        'ConnectToStatsShorty2' => array(     // mysql -h 192.168.30.39 -u c3slave -pRstG496urky2 Shorty
            'host' => '192.168.16.42',
            'user' => 'c3slave',
            'pass' => 'RstG496urky2',
            'db' => 'Shorty'
        ),
        'LiveRead' => array(
            'host' => array("192.168.30.104", "192.168.30.105"),
            'user' => 'c3slave',
            'pass' => 'RstG496urky2',
            'db' => 'Live'
        ),
        'ShortyWrite' => array(
            'host' => array("192.168.16.4", "192.168.16.7", /*"192.168.16.8",*/ "192.168.16.9"),
            'user' => 'c3slave',
            'pass' => 'RstG496urky2',
            'db' => 'Shorty'
        ),
        'ShortyWrite1' => array(
            'host' => '192.168.16.4',
            'user' => 'c3slave',
            'pass' => 'RstG496urky2',
            'db' => 'Shorty'
        ),
        'slaveLP' => array(
            //'host' => array("192.168.16.5", "192.168.16.6"),
            // 'host' => "192.168.16.159",
            'host' => "129.80.64.116",
            'user' => 'c3slave',
            'pass' => 'RstG496u*#rky2',
            'db' => 'local_pages'
        ),
        'StatsMasterlive' => array(
            'host' => array("192.168.30.104", "192.168.30.105"),
            'user' => 'c3slave',
            'pass' => 'RstG496urky2',
            'db' => 'Live'
        ),
        'pointcombiz' => 'pointcom_oci.ini',
        'ConnectToTempAdmin' => array(
            'host' => '192.168.21.190',
            'user' => 'temp_admin_readonly_user',
            'pass' => '7wyfikjhdgskugfc',
            'db' => 'Admin'
        ),
    );
    public static function loadConst()
    {
        global $admin_conf,$search_conf,$shorty_conf,$keywords_conf,$adcenter_conf,$stats,$archive_conf,$whale_conf,$cms_conf,$email_whois_conf,$rtb_conf,$localpages,$the_agency,$attestpath_conf,$webcrawlerdb_conf;
        self::$access['ConnectToAdmin'] = empty($admin_conf) ? 'adDbfileNew.ini' : $admin_conf;
        self::$access['ConnectToAttestpath'] = empty($attestpath_conf) ? 'attestpath_oci.ini' : $attestpath_conf;
        self::$access['ConnectToWebcrawlerdb'] = empty($webcrawlerdb_conf) ? 'webcrawler_oci.ini' : $webcrawlerdb_conf;
        self::$access['ConnectToSearch'] = empty($search_conf) ? array('host' => '192.168.30.4', 'user' => 'searchdbuser', 'pass' => 'S7#234D@asSRCH', 'db' => 'search') : $search_conf;
        self::$access['ConnectToNewAdmin110'] = empty($admin_conf) ? 'adDbfileNew.ini' : $admin_conf;
        self::$access['ConnectToWhale'] = empty($whale_conf) ? 'whale51046.ini' : $whale_conf;
        self::$access['ConnectToArchive'] = empty($archive_conf) ? 'arch.ini' : $archive_conf;
        self::$access['ConnectToKeywords'] = empty($keywords_conf) ? 'keywords.ini' : $keywords_conf;
        self::$access['ConnectToStatsShorty'] = empty($shorty_conf) ? 'shorty_oci.ini' : $shorty_conf;
        self::$access['Stats'] =  empty($stats) ? 'statsDb2060.ini' : $stats;
        self::$access['AdcenterStats'] =  empty($adcenter_conf) ? 'adCenterDbFile2020.ini' : $adcenter_conf;
        self::$access['ConnectToCMS'] =  empty($cms_conf) ? 'cms.ini' : $cms_conf;
        self::$access['StatsRtb'] =  empty($rtb_conf) ? array('host' => '192.168.17.111','user' => 'c3slave','pass' => 'RstG496u*#rky2','db' => 'rtb') : $rtb_conf;
        self::$access['StatsRtb2'] =  empty($rtb_conf) ? array('host' => '192.168.17.30','user' => 'c3slave','pass' => 'RstG496u*#rky2','db' => 'rtb') : $rtb_conf;
        self::$access['email_whois'] =  empty($email_whois_conf) ? array('host' => '192.168.16.20','user' => 'c3slave','pass' => 'RstG496urky2','db' => 'email_whois') : $email_whois_conf;
        self::$access['MasterLP'] = empty($localpages) ? array('host' => '192.168.30.115','user' => 'c3slave','pass' => 'RstG496u*#rky2','db' => 'local_pages') : $localpages;
        self::$access['Agency'] = $the_agency;
    }
    public static function connect($connectionName)
    {
        self::loadConst();
        if (!isset(self::$db[$connectionName])) {

            if (is_string(self::$access[$connectionName])) {
                $credentials = parse_ini_file(self::$access[$connectionName]);
            } else {
                $credentials = self::$access[$connectionName];
            }

            if (is_array($credentials['host'])) {
                shuffle($credentials['host']);
                $credentials['host'] = $credentials['host'][0];
            }

            $connectionData = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $credentials['host'], $credentials['db']);

            try {
                self::$db[$connectionName] = new PDO($connectionData, $credentials['user'], $credentials['pass']);
            } catch (PDOException $e) {
                self::$error = $e->getMessage();
                return false;
            }
        }

        return self::$db[$connectionName];

    }
    /**
     * Call function when  needed a persistance connection
     * @param type $connectionName conection string name
     * @return boolean resource id
     */
    public static function pconnect($connectionName)
    {
        self::loadConst();
        if (!isset(self::$dbPersistence[$connectionName])) {

            if (is_string(self::$access[$connectionName])) {
                $credentials = parse_ini_file(self::$access[$connectionName]);
            } else {
                $credentials = self::$access[$connectionName];
            }

            if (is_array($credentials['host'])) {
                shuffle($credentials['host']);
                $credentials['host'] = $credentials['host'][0];
            }

            $connectionData = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $credentials['host'], $credentials['db']);

            try {
                self::$dbPersistence[$connectionName] = new PDO($connectionData, $credentials['user'], $credentials['pass'], array(PDO::ATTR_PERSISTENT => true));
            } catch (PDOException $e) {
                self::$error = $e->getMessage();
                return false;
            }
        }

        return self::$dbPersistence[$connectionName];

    }
	public static function run($IGNORE_LIST) {
        self::loadConst();
		$msg = "";
		if (count(self::$access)) {
			foreach (self::$access as $db_name => $credentials) {
				if (!is_array($credentials)) {
					$credentials = parse_ini_file($credentials);
				}
				if (!is_array($credentials['host'])) {
					$credentials['host'] = array($credentials['host']);
				}
				foreach ($credentials['host'] as $host) {
					if (in_array($db_name, array_keys($IGNORE_LIST)) && in_array($host, $IGNORE_LIST[$db_name])) {
						continue;
					}
					$connectionData = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $host, $credentials['db']);
					try {
						new PDO($connectionData, $credentials['user'], $credentials['pass'], array(PDO::ATTR_PERSISTENT => true));
					} catch (PDOException $e) {
						$temp_credential = $credentials;
						unset($temp_credential['host']);
						print "DB : $db_name, Host : $host, ERR : " . $e->getMessage() . ", CREDENTIAL : " . json_encode($temp_credential) . "\n";
						unset($temp_credential['pass']);
						$msg .= "DB : *$db_name*, Host : *$host*, ERR : *" . $e->getMessage() . "*, CREDENTIAL : " . json_encode($temp_credential) . "\n\n";
					}
				}
			}
		}
		return $msg;
	}

}