<?php

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

class Account extends Common {
  private $common;
  private $count;

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

  public function index ($id, $cat='video-channels', $page=0) {
    $res = [
      'page' => 'account',
      'style' => 'account',
      'cat' => $cat,
      'paginate' => $page,
      'pagetotal' => 500,
      'userinfo' => $this->common->user,
    ];

    $res['owner'] = $this->getOwner($id);
    if (!empty($res['owner'])) $res['owner']->totalVideo = 0;
    $res['channel'] = $this->getChannel($id, $cat, ($page*$this->count), $this->count);
    if (!empty($res['owner'])) {
      if ($cat == 'video-channels') {
        $stats = $this->ptapi('/api/v1/accounts/'.$id.'/videos?start=0&count=0&skipCount=false&nsfw=both');
        $res['owner']->totalVideo = $stats->total;
        foreach ($res['channel']->data as $k => $v) {
          $res['channel']->data[$k]->video = $this->getVideo($v->name.'@'.$v->host);
          $res['owner']->followersCount += $v->followersCount;
        }
      }
      else {
        $stats = $this->ptapi('/api/v1/accounts/'.$id.'/video-channels?start=0&count=20');
        $res['owner']->totalVideo = $res['channel']->total;
        foreach ($stats->data as $k => $v) {
          $res['channel']->data[$k]->video = $this->getVideo($v->name.'@'.$v->host);
          $res['owner']->followersCount += $v->followersCount;
        }
      }
    }

    return view('pages.peertube.a', ['res' => $res, 'cat' => $cat]);
  }

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

  function getChannel ($id, $cat, $start, $count) {
    if ($cat == 'video-channels') $count = 5;
    $sort = $cat == 'video-channels' ? '-updatedAt&withStats=false' : '-publishedAt&skipCount=false&nsfw=both';
    return $this->ptapi('/api/v1/accounts/'.$id.'/'.$cat.'?start='.$start.'&count='.$count.'&sort='.$sort);
  }

  function getVideo ($id) {
    return $this->ptapi('/api/v1/video-channels/'.$id.'/videos?start=0&count=5&sort=-publishedAt&skipCount=false&nsfw=both');
  }
}
