<?php

namespace Drupal\ufc\Services;

use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\Cache;
use Drupal\media\Media;
use Drupal\ufc\Fighter;
use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;

class FighterImporter {

  /**
   * Guzzle http client service.
   *   @var \GuzzleHttp\Client
   */
  protected $httpClient;

  /**
   * Entity type manager service.
   *   @var \Drupal\Core\Entity\EntityTypeManager
   */
  protected $entityTypeManager;

  /**
   * The UFC cache bin.
   */
  protected $cache;

  /**
   * Array of all fighters.
   *  @var array[]
   */
  public $fighters = [];

  public $cookieJar;

  /**
   * The base url for fighter lists.
   *  @var string
   */
  const UFC_BASE = "https://www.ufc.com/jsonapi/node/athlete";

  /**
   * Public constructor for Fighter Importer.
   *
   * @param Client $httpClient
   * @param EntityTypeManager $entityTypeManager
   * @param Cache $cache
   */
  public function __construct(
    Client $httpClient,
    EntityTypeManager $entityTypeManager,
    CacheBackendInterface $cache
  ) {
    $this->httpClient = $httpClient;
    $this->entityTypeManager = $entityTypeManager;
    $this->cache = $cache;
  }

  /**
   * Get list of current fighters.
   *
   * @return array $fighters
   */
  public function getListOfCurrentFighters(): array {
    $this->addFightersFromUrl(self::UFC_BASE);
    return $this->fighters;
  }

  /**
   * Add fighters from a URL.
   *
   * @param string $url
   *   The URL to scrape.
   */
  public function addFightersFromUrl(string $url) {
    sleep(10);
    dump("Requesting: " . $url);
    $proxied_url = 'http://192.168.0.13:8888/?url=' . urlencode($url);
    $ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Safari/605.1.15';
    $headers = [
      'referer' => true,
      'verify' => false,
      'headers' => [
        'User-Agent' => $ua,
        'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding' => 'gzip, deflate, br',
        'Cache-Control' => 'no-cache',
        'Pragma' => 'no-cache',
        'Referer' => 'https://www.ufc.com/athletes/all',
      ]
    ];
    $response = $this->httpClient->request('GET', $proxied_url, $headers);
    $content = $response->getBody()->getContents();
    $content_arr = json_decode($content, TRUE);

    if (!$content_arr) {
      exit("something went wrong");
    }

    $athletes = $content_arr['data'];
    $count = count($athletes);
    dump("Found " . $count . " fighters.");
    foreach ($athletes as $athlete) {
      $this->fighters[] = $athlete;
    }
    $next_page = $content_arr['links']['next']['href'] ?? FALSE;
    if ($next_page) {
      $this->addFightersFromUrl($next_page);
    }
  }

  /**
   * There is a pager, loop through to get all fighters.
   *
   * @param string $base_url
   */
  public function importFighters(): void {
    // Get JSON File from API.
    $api_athletes = $this->cache->get('ufc_api_athletes');
    if (!$api_athletes) {
      echo "Go get api data!";
      exit();
    }
    // This includes all fighters in data.
    // Iterate over data to import all fighters.
  }


  /**
   * There is a pager, loop through to get all fighters.
   *
   * @param string $base_url
   */
  public function loopThroughFighterPages($base_url): void {
    // Implement caching to store instead of needing fresh requests.
    for ($i=0; $i<=10; $i++) {
      $ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Safari/605.1.15';
      $headers = [
        'referer' => true,
        'verify' => false,
        'headers' => [
          'User-Agent' => $ua,
          'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
          'Accept-Encoding' => 'gzip, deflate, br',
          'Cache-Control' => 'no-cache',
          'Pragma' => 'no-cache',
          'Referer' => 'https://www.ufc.com/athletes/all',
        ]
      ];
      $url = $base_url . "&page=$i&_=" . microtime(true);
      $response = $this->httpClient->request('GET', $url, $headers);
      dump($url);
      $content = $response->getBody()->getContents();
      dump($response->getStatusCode());
      $invalid_page = strpos($content, "No Result Found For");
      if (!$invalid_page) {
        \Drupal::logger('ufc')->notice("Extracting fighters from page $i.");
        continue;
      }
      break;
    }
  }

}
