<?php

namespace App\Http\Controllers\Peertube;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Engine;
// use Illuminate\Support\Facades\Log;

class Common extends Engine {
  public $user = [];
  private $engine;

  public function __construct () {
    $this->user['local'] = $this->getLocal();
    $this->user['me'] = $this->getMe();
    $this->user['notify'] = $this->getNotify();
    $this->engine = new Engine;
  }

  public function getLocal () {
    return null;
    return $this->ptapi_get('/api/v1/oauth-clients/local');
  }

  public function getMe () {
    return null;
    return $this->ptapi_get('/api/v1/users/me');
  }

  public function getNotify () {
    return null;
    return $this->ptapi_get('/api/v1/users/me/notifications?start=0&count=0&unread=true');
  }

  public function ptapi_get ($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, env('PEER_URI').$url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $get = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if (!$get) return $err;
    $get = json_decode($get);
    if (isset($get->status) && $get->status == 404) return [];

    return $get;
  }

  public function vidlist ($get) {
    $res = [
      'today' => [],
      'week' => [],
      'month' => [],
      'lastmonth' => [],
      'moreearly' => [],
    ];

    foreach ($get->data as $g) {
      $ud = strtotime($g->createdAt);

      if ($ud > time() - 86400 && $ud < time() + 86400) $res['today'][] = $g;
      else if ($ud > time() - 604800 && $ud < time() + 604800) $res['week'][] = $g;
      else if ($ud > time() - 2629800 && $ud < time() + 2629800) $res['month'][] = $g;
      else if ($ud > time() - 5259600 && $ud < time() + 5259600) $res['lastmonth'][] = $g;
      else $res['moreearly'][] = $g;
    }

    return $res;
  }
}
