<?php

namespace Drupal\nodehive_core;

use Drupal\Core\File\FileExists;
use Drupal\Core\File\FileSystemInterface;
use Drupal\file\FileRepositoryInterface;
use Sabberworm\CSS\Parser;

/**
 * Parses the external CSS and makes it CKEditor 5 compatible.
 */
class CKEditor5ExternalCssParser implements CKEditor5ExternalCssParserInterface {

  /**
   * The file system.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * The file repository.
   *
   * @var \Drupal\file\FileRepositoryInterface
   */
  protected $fileRepository;

  /**
   * Constructs an MenuHelper object.
   *
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system.
   * @param \Drupal\file\FileRepositoryInterface $file_repository
   *   The file repository.
   */
  public function __construct(
    FileSystemInterface $file_system,
    FileRepositoryInterface $file_repository,
  ) {
    $this->fileSystem = $file_system;
    $this->fileRepository = $file_repository;
  }

  /**
   * {@inheritdoc}
   */
  public function parseCss(string $url) {
    $content = $this->getCssContent($url);
    $parser = new Parser($content);
    $css_document = $parser->parse();

    $ckeditor_class = ".ck-content";
    foreach ($css_document->getAllDeclarationBlocks() as $block) {
      foreach ($block->getSelectors() as $selector) {
        // Check if the selector already starts with ".ck-content".
        if (strpos($selector->getSelector(), $ckeditor_class) !== 0) {
          $selector->setSelector($ckeditor_class . ' ' . $selector->getSelector());
        }
      }
    }

    $folder_path = 'public://nodehive_core/';
    $filename = 'ckeditor5_styles.css';
    if ($this->fileSystem->prepareDirectory($folder_path, FileSystemInterface::CREATE_DIRECTORY)) {
      $this->fileRepository
        ->writeData(
          $css_document->render(),
          $folder_path . '' . $filename,
          FileExists::Replace
        );
    }
  }

  /**
   * Gets the external CSS contents.
   *
   * @param string $url
   *   External CSS url.
   *
   * @return string
   *   Returns CSS contents.
   */
  protected function getCssContent(string $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
  }

}
