<?php
###############################################################################
# ImportManager.php
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
############################################################################### 

namespace 	CodePunch\DB;
use 		CodePunch\Base\Util as UTIL;
use			CodePunch\Base\Text as TEXT;
use			CodePunch\DB\Audit as AUDIT;
use			Exception;

###############################################################################

class ImportManager  {
	
	private $authentication = null;
	private $profile = null;
	private $categoryids = array();
	private $responce = array();
	private $supportswhois = false;
	
	###########################################################################
	
	public function __construct($auth=null) {
		$this->authentication = $auth;
		$this->responce['added'] = 0;
		$this->responce['failed'] = 0;
		$this->responce['existing'] = 0;
		$this->responce['subdomains'] = 0;
		$this->responce['cids'] = 0;
	}
	
	###########################################################################
	
	public function getAuthentication() {
		return $this->authentication;
	}
	
	###############################################################################
	
	public function importDomains($domain, $index, $domaindata)
	{
		$count = count($domaindata);
		if($count) {
			$info = $this->addDomains($domaindata, $this->categoryids, $this->supportswhois ? $this->profile : "");
			$this->responce['added'] += $info['added'];
			$this->responce['failed'] += $info['failed'];
			$this->responce['existing'] += $info['existing'];
			$this->responce['subdomains'] += $info['subdomains'];
			$this->responce['cids'] += $info['cids'];
			if(UTIL::is_in_debug_mode())
				UTIL::cli_print($domaindata);
			else
				UTIL::cli_print($domain);
		}
		return \CodePunch\LU\Registrars\RegistrarAPI::REGAPI_CONTINUE;
	}
	
	###############################################################################
	
	public function importDomainsFromRegistrar($apiprofile, $cid=array())
	{
		$this->profile = $apiprofile;
		$this->categoryids = $cid;
		$this->supportswhois = false;
		$supportswhois = false;
		$ci = $this->getAuthentication()->getDatabase()->getRegistrarAPIClass($apiprofile, $this->getAuthentication());
		if($ci['class'] != "" && count($ci['params'])) {
			try {
				$connManager = new \CodePunch\LU\ConnectionManager($this->getAuthentication());
				$regapi = new $ci['class']($connManager, ...$ci['params']);
				// Check if the API supports whois lookup.
				$supported = $regapi->supported();
				if(is_array($supported) && in_array("whois", $supported))
					$this->supportswhois = true;
				$dlist = $regapi->domainlist(array($this, 'importDomains'));
			}
			catch(Exception $e) {
				$logger = new \CodePunch\Base\CPLogger();
				$emsg =  "Unable to import domains from $apiprofile (" . $e->getMessage() . ")";
				$logger->error($emsg);
				UTIL::debug_cli_print($emsg);
			}
		}
		else
			throw new Exception("Unable to find a profile or data source named '$apiprofile'");
		return $this->responce;
	}
	
	###############################################################################
	
	public function getDomainsFromRegistrar($apiprofile, &$supportswhois)
	{
		$dlist = array();
		$supportswhois = false;
		$ci = $this->getAuthentication()->getDatabase()->getRegistrarAPIClass($apiprofile, $this->getAuthentication());
		if($ci['class'] != "" && count($ci['params'])) {
			try {
				$connManager = new \CodePunch\LU\ConnectionManager($this->getAuthentication());
				$regapi = new $ci['class']($connManager, ...$ci['params']);
				// Check if the API supports whois lookup.
				$supported = $regapi->supported();
				if(is_array($supported) && in_array("whois", $supported))
					$supportswhois = true;
				$dlist = $regapi->domainlist();
			}
			catch(Exception $e) {
				$logger = new \CodePunch\Base\CPLogger();
				$emsg =  "Unable to import domains from $apiprofile (" . $e->getMessage() . ")";
				$logger->error($emsg);
			}
		}
		return implode("\n", $dlist);
	}
	
	###############################################################################
	
	public function addDomains($domaindata, $cids, $profile="")
	{
		$info = array('added'=>0, 'failed'=>0);
		
		$auth = $this->authentication;
		$db = $auth->getDatabase();
		if(!is_array($domaindata)) 
			$domaindata = explode("\n", $domaindata);
		$domains = array();
		foreach($domaindata as $domain) {
			$dinfo = $domain;
			if(is_array($domain)) 
				$domain = $dinfo['domain'];
			$domain = trim($domain);
			if(!UTIL::starts_with($domain, ".") && !UTIL::ends_with($domain, ".") && strpos($domain, ".") !== false) 
				$domains[]  = $dinfo;
		}
		
		if(count($domains)) {
			$ai = $db->addDomains($domains, $profile, $cids, $this->profile);
			
			$info['added'] = count($ai['added']);
			$info['existing'] = count($ai['existing']);
			$info['subdomains'] = count($ai['sds']);
			$info['cids'] = count($ai['cids']);
			$info['failed'] = 0;
			
			if(count($ai['added'])) {
				$auditinfo = array();
				$lookup = new \CodePunch\LU\LookupManager($auth);
				$setup = new \CodePunch\Config\Settings($auth);
				foreach($ai['added'] as $sid) {
					$status = $lookup->addDefaultLookups($sid);
					$failures = 0;
					foreach($status as $s) {
						if(!$s)
							$failures++;
					}
					$sddata = $setup->getOption('default_sub_domains', "");
					if($db->addDefaultSubdomains($sid, $sddata) !== true)
						$failures++;
					if($failures)
						$info['failed'] = $failures;
					if(count($auditinfo) < 25)
						$auditinfo[] = $db->getDomainName($sid);
				}
				$formatted = UTIL::implode_limited(",", $auditinfo, 20);
				AUDIT::add($db, AUDIT::ADD_DOMAINS, count($ai['added']) . " domains imported from " . $this->profile, $formatted);
			}
		}
		return $info;
	}
}