<?php

namespace Eater\Glim\Service;

use Stash\Pool;

class GitHub extends Main
{
    public function getContributors() {

        /** @var Pool $pool */
        $pool = $this->get('stash');

        $contributors = $pool->getItem('github/contributors');

        if ($contributors->isMiss()) {
            $contributorsData = [];

            try {
                $contributorsJson = @$this->fetch('/repos/' . $this->get('github-repo') . '/contributors');
                $contributorsNewData = json_decode($contributorsJson, true);
                if ($contributorsNewData !== null) {
                    $contributorsData = $contributorsNewData;
                }
            } catch (\Exception $e) {
            }

            $info = $this->getRepoInfo();

            if ($info !== false) {

                $ownerId = $info['owner']['id'];

                $contributorsNewData = [];

                foreach ($contributorsData as $contributor) {
                    if ($contributor['id'] !== $ownerId) {
                        $contributorsNewData[] = $contributor;
                    }
                }

                $contributorsData = $contributorsNewData;
            }

            $contributors->expiresAfter(3600);
            $contributors->set($contributorsData);
            $contributors->save();
        }

        return $contributors->get();
    }

    public function getRepoInfo() {
        /** @var Pool $pool */
        $pool = $this->get('stash');

        $info = $pool->getItem('github/info');

        if ($info->isMiss()) {
            $infoData = false;

            try {
                $infoJson = @$this->fetch('/repos/' . $this->get('github-repo'));
                $infoNewData = json_decode($infoJson, true);
                if ($infoNewData !== null) {
                    $infoData = $infoNewData;
                }
            } catch (\Exception $e) {
            }

            $info->expiresAfter(3600);
            $info->set($infoData);
            $info->save();
        }

        return $info->get();
    }

    private function fetch($path)
    {
        $options  = array('http' => array('user_agent'=> $_SERVER['HTTP_USER_AGENT']));
        $context  = stream_context_create($options);
        return file_get_contents('https://api.github.com' . $path, false, $context);
    }
}