<?php

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

class Watch extends Common {
  private $common;

  public function __construct () {
    $this->common = new Common;
  }

  public function index ($id) {
    $res = [
      'page' => 'watch',
      'style' => 'watch',
      'userinfo' => $this->common->user,
    ];
    $res['detail'] = $this->getDetail($id);
    $res = $this->getComment($id, $res);

    $tags = [];
    if (!is_null($res['detail']->tags)) $tags = $res['detail']->tags;
    else $tags = explode(' ', $res['detail']->title);

    $res['recommend'] = $this->getRecommend($tags);
    return view('pages.peertube.w', ['res' => $res]);
  }

  function getDetail ($id) {
    return $this->ptapi('/api/v1/videos/'.$id);
  }

  function getRecommend ($tags) {
    $tag = '';
    foreach ($tags as $t) {
      $tag .= 'tagsOneOf='.urlencode($t).'&';
    }
    return $this->ptapi('/api/v1/search/videos?start=0&count=6&nsfw=both&'.$tag.'sort=-publishedAt&searchTarget=local');
  }

  function getComment ($id, $res) {
    $get = null;

    $res['comment'] = $this->ptapi('/api/v1/videos/'.$id.'/comment-threads');
    foreach ($res['comment']->data as $co) {
      $co->src = 'PT';
    }

    return $res;
  }
}
