<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Service\Mail;

class SmtpMailer extends \StevenBuehner\sbChurchtoolsGrouphomepage\Vendor\Nette\Mail\SmtpMailer {

	// Check only once ...
	protected $credentialsCheckedSuccessfully = NULL;
	protected $from                           = NULL;

	public function __construct(array $options = []) {
		$host       = isset($options['host']) ? (string)$options['host'] : '';
		$username   = isset($options['username']) ? (string)$options['username'] : '';
		$password   = isset($options['password']) ? (string)$options['password'] : '';
		$port       = isset($options['port']) && $options['port'] !== '' ? (int)$options['port'] : NULL;
		$secure     = isset($options['secure']) ? strtolower((string)$options['secure']) : '';
		$encryption = NULL;
		$timeout    = isset($options['timeout']) && $options['timeout'] !== '' ? (int)$options['timeout'] : 20;

		if ($secure === 'ssl') {
			$encryption = self::EncryptionSSL;
		} elseif ($secure === 'tls') {
			$encryption = self::EncryptionTLS;
		}

		parent::__construct($host, $username, $password, $port, $encryption, FALSE, $timeout);

		if (isset($options['username']) && is_email($options['username'])) {
			$this->from = $options['username'];
		}

	}

	protected function connect(): void {
		// TODO: Get Connection-Settings
		parent::connect();
	}

	public function credentialsValid() {

		if ($this->credentialsCheckedSuccessfully === TRUE || $this->credentialsCheckedSuccessfully === FALSE) {
			return $this->credentialsCheckedSuccessfully;
		}

		try {
			$this->connect();
			$this->credentialsCheckedSuccessfully = TRUE;
		} catch (\Exception $e) {
			$this->credentialsCheckedSuccessfully = FALSE;
		}

		return $this->credentialsCheckedSuccessfully;

	}

	public function getFrom() {
		return $this->from;
	}


}
