<?php

namespace App\Services;

class GiteaService
{
    private $cacheFile = null;
    private $config = [];

    public function __construct()
    {
        $this->config = config('services.gitea');
        $this->cacheFile = storage_path('app/gitea_cache.txt');
    }

    public function checkForLatestRelease()
    {
        $cacheData = null;

        if ($this->doesCacheExist())
        {
            // Get the etag from the cache
            $cacheData = $this->getCacheData();
        }
        else
        {
            // Lookup and store the version information
            $statusCode = -1;
            $result = $this->getLatestReleaseFromGitea($statusCode);

            if ($statusCode == 200)
            {
                $releases = json_decode($result[1]);

                $latestRelease = null;
                foreach ($releases as $release)
                {
                    if (is_null($latestRelease) || version_compare($release->tag_name, $latestRelease->tag_name) > 0)
                    {
                        $latestRelease = $release;
                    }
                }

                $cacheData = $this->setCacheData($latestRelease);
            }
        }

        // GitHub compatibility
        $cacheData->html_url = sprintf($this->config['releases_url'], $this->config['repo_owner'], $this->config['repo_name']);

        return $cacheData;
    }

    private function doesCacheExist()
    {
        $exists = file_exists($this->cacheFile);

        if ($exists)
        {
            // Check modified time on the file
            $stat = stat($this->cacheFile);

            $diff = time() - $stat['mtime'];
            if ($diff > $this->config['cache_time_seconds'])
            {
                $exists = false;
            }
        }

        return $exists;
    }

    private function getCacheData()
    {
        return json_decode(file_get_contents($this->cacheFile));
    }

    private function getLatestReleaseFromGitea(&$statusCode)
    {
        $httpHeaders = [
            sprintf('User-Agent: aheathershaw/blue-twilight (v%s)', config('app.version'))
        ];

        if (isset($this->config['api_key']) && !empty($this->config['api_key']))
        {
            $httpHeaders[] = sprintf('Authorization: %s', $this->config['api_key']);
        }

        $apiUrl = sprintf('%s/repos/%s/%s/releases', $this->config['api_url'], $this->config['repo_owner'], $this->config['repo_name']);

        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);

        if ($result === false)
        {
            throw new \Exception(sprintf('Error from Gitea: %s', curl_error($ch)));
        }

        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return explode("\r\n\r\n", $result, 2);
    }

    private function setCacheData($data)
    {
        file_put_contents($this->cacheFile, json_encode(get_object_vars($data)));
        return $data;
    }
}