<?php

declare(strict_types=1);

namespace mirzaev\huesos\models\traits\yandex;

// Framework for PHP
use mirzaev\minimal\http\enumerations\content;

// Built-in libraries
use exception;

/**
 * Trait for "Yandex Disk"
 *
 * @package mirzaev\huesos\models\traits\yandex
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
trait disk
{
	/**
	 * Download file from "Yandex Disk"
	 *
	 * @param string $uri URI of the file from "Yandex Disk"
	 * @param string $destination Destination to write the file
	 * @param string|int $name Name for the file
	 * @param array &$errors Registry of errors
	 *
	 * @return array|false The [destination, name, content] of the downloaded file, if the file was downloaded
	 */
	private static function download(
		string $uri,
		string $destination,
		string|int $name,
		array &$errors = []
	): array|false {
		try {
			if (!empty($uri)) {
				// Not empty URI

				if (!empty($destination)) {
					// Not empty destination

					// Initializing URL of the file
					$url = "https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key=$uri";

					// Checking if the file is available for download
					$session = curl_init($url);
					curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
					curl_exec($session);
					$code = curl_getinfo($session, CURLINFO_RESPONSE_CODE);
					curl_close($session);

					if ($code === 200) {
						// The file is available for download

						// Initializing URI of the file
						$uri = json_decode(file_get_contents($url))?->href;

						// Downloading the file
						$session = curl_init($uri);
						curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
						curl_setopt($session, CURLOPT_AUTOREFERER, true);
						curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
						curl_exec($session);
						$file = curl_exec($session);
						$code = curl_getinfo($session, CURLINFO_RESPONSE_CODE);
						preg_match('/^\w+\/\w+/', curl_getinfo($session, CURLINFO_CONTENT_TYPE), $matches);
						$type = content::from($matches[0]);
						curl_close($session);

						if ($code === 200 && $file) {
							// The file is downloaded

							if ($type instanceof content) {
								// Initialized content-type header

								if (file_put_contents($destination . DIRECTORY_SEPARATOR . "$name." . $type->extension(), $file) > 0) {
									// Downloaded the file

									// Exit (success)
									return ['destination' => $destination, 'name' => $name, 'content' => $type];
								}
							} else throw new exception("Failed to initialize content-type header");
						} else throw new exception("Failed to download the file by link: $uri");
					} else throw new exception("File not available for download: $uri");
				} else throw new exception("Empty destination");
			} else throw new exception("Empty URI");
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return false;
	}
}
