<?php

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

class Prayer extends Engine {
  private $engine;

  public function __construct () {
    $this->engine = new Engine;
  }

  public function index ($vid) {
    $res = DB::table('vid_video')->where('vid', $vid)->first();
    if (!$res) return view('pages.site.notfound');
    $game = DB::table('vid_game')->where('id', $res->game_id)->first();
    if (!$game) return view('pages.site.notfound');

    $res->publish_date = date('Y月m月d日', $res->publish_date);
    $res->gametitle = explode('】', $res->title);
    $res->title = $res->gametitle[1];
    $res->gametitle = $res->gametitle[0];
    $res->gametitle = str_replace('【'.$game->name, '', $res->gametitle);
    $res->mgametitle = $game->name;
    $slugger = $res->vid;
    $res->slug = $game->slug;
    $res->pageslug = $vid;

    if ($res->gametitle == '') $res->gametitle = '初代';

    $comments = DB::table('blg_comments')->where('video_id', $vid)->orderBy('id', 'asc')->get()->toArray();
    $ytslug = explode('?v=', $res->youtube);
    $res->ytcomment = (isset($ytslug[1]) ? $this->getYouTubeCome($ytslug[1], $slugger) : array());
    if (isset($res->ytcomment['nextPage']) && $res->ytcomment['nextPage'] != '') {
      while ($res->ytcomment['nextPage'] != '') {
        $res->ytcomment = $this->checkYouTubeCome($res->ytcomment, $ytslug[1], $res->ytcomment['nextPage']);
      }
    }

    $res->kvcomment = array();
    $kvslug = explode('/', $res->kerotube);
    if (isset($kvslug[5]) && $kvslug[3] == 'videos') {
      DB::table('vid_video')->where('vid', $res->vid)->update(['kerotube' => 'https://video.076.ne.jp/w/'.$kvslug[5]]);
      $kvslug = explode('/', $res->kerotube);
    }
    if (isset($kvslug[4])) {
      $res->kvcomment = $this->getPeerCome($kvslug[4], '');
    }

    if ($res->ytcomment) $res->ytcomment = $this->backupYTComment($slugger, $res->ytcomment);
    $res->lbcomment = array();
    if ($res->kvcomment) $res->kvcomment = $this->backupPeerComment($slugger, $res->kvcomment);

    foreach ($comments as $k => $c) {
      $c->replyCount = 0;
      $c->isvideo = 't';
      $c->src = 'TS';

      if (!is_null($c->user_id) && !empty(userDetail($c->user_id))) {
        $det = userDetail($c->user_id);
        $c->user_id = $det['user_id'];
        $c->showname = $det['showname'];
        $c->showcol = $det['showcol'];
        $c->avatar = $det['avatar'];
      }

      unset($c->email);
      unset($c->ipaddress);
      unset($c->isShadow);
      $c->created = date('Y年m月d日 H:i:s', $c->created);
    }

    $res->user = userDetail(null, (isset($_COOKIE['kero_token']) ? $_COOKIE['kero_token'] : ''));
    $res->comments['total'] = count($comments);
    $res->comments['come'] = $comments;
    $res->comments['total'] += (isset($res->ytcomment['total']) ? $res->ytcomment['total'] : 0);
    $res->comments['total'] += (isset($res->kvcomment['total']) ? $res->kvcomment['total'] : 0);
    if (isset($res->ytcomment['come'])) $res->comments['come'] = array_merge($res->comments['come'], $res->ytcomment['come']);
    if (isset($res->kvcomment['come'])) $res->comments['come'] = array_merge($res->comments['come'], $res->kvcomment['come']);

    DB::table('vid_video')->where('vid', $vid)->update(['view' => $res->view+1]);

    return view('pages.site.video.prayer', ['res' => $res, 'user' => $this->user]);
  }

  function getPeerCome ($slug, $tslug) {
    $come = [];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, env('PEER_URI').'/api/v1/videos/'.$slug.'/comment-threads');
    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);

    $come = array();
    $come['come'] = array();

    if (isset($get->error) || !$get) {
      if ($tslug != '') {
        if (!$get = DB::table('vid_kerocomment')->where('vid', $tslug)->first()) return array();
        $come = unserialize($get->come);
        return $come;
      }
    }

    if (isset($get->data)) {
      foreach ($get->data as $g) {
        $g->comments = new \stdClass();
        $g->comments->id = $g->id;
        $g->comments->name = $g->account->displayName;
        $g->comments->channel = $g->account->url;
        $g->comments->icon = env('PEER_URI').$g->account->avatar->path;
        $g->comments->message = strip_tags($g->text, array('<br />'));
        $g->comments->createdTS = strtotime($g->createdAt);
        $g->comments->created = date('Y年m月d日 H:i:s', strtotime($g->createdAt));
        $g->comments->replyCount = (isset($g->totalReplies) ? $g->totalReplies : 0);
        $g->comments->isvideo = 'n';
        $g->comments->src = '076';

        $come['come'][] = $g->comments;
      }
    }

    $come['total'] = $get->totalNotDeletedComments;

    return $come;
  }

  function checkYouTubeCome ($res, $slug, $next='') {
    $come = $this->getYouTubeCome($slug, '', $next);
    foreach ($come['come'] as $com) { $res['come'][] = $com; }
    $res['total'] += $come['total'];
    $res['nextPage'] = $come['nextPage'];

    return $res;
  }

  function getYouTubeCome ($slug, $tslug, $page='') {
    $ch = curl_init();
    $url = 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&moderationStatus=published&videoId='.$slug.'&key='.env('YOUTUBE_API').'&pageToken='.$page;//.'&order=date&pageToken='.$page;

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

    $come = array();
    $get = json_decode($get, false);
    $come['come'] = array();

    if (isset($get->error) || !$get) {
      if ($tslug != '') {
        if (!$get = DB::table('vid_ytcomment')->where('vid', $tslug)->first()) return array();
        $come = unserialize($get->come);
        return $come;
      }
    }

    foreach ($get->items as $g) {
      $g->comment = new \stdClass();
      $g->comment->id = $g->id;
      $g->comment->name = $g->snippet->topLevelComment->snippet->authorDisplayName;
      $g->comment->channel = $g->snippet->topLevelComment->snippet->authorChannelUrl;
      $g->comment->icon = $g->snippet->topLevelComment->snippet->authorProfileImageUrl;
      $g->comment->createdTS = strtotime($g->snippet->topLevelComment->snippet->publishedAt);
      $g->comment->created = date('Y年m月d日 H:i:s', strtotime($g->snippet->topLevelComment->snippet->publishedAt));
      $g->comment->message = strip_tags($g->snippet->topLevelComment->snippet->textDisplay, array('<br />'));
      $g->comment->replyCount = (isset($g->snippet->totalReplyCount) ? $g->snippet->totalReplyCount : 0);
      $g->comment->isvideo = 'n';
      $g->comment->src = 'YT';

      if (isset($g->replies)) {
        $g->comment->replies = array();
        foreach ($g->replies->comments as $k => $c) {
          $g->comment->replies[$k]['id'] = (isset($c->id) ? $c->id : $c['id']);
          $g->comment->replies[$k]['name'] = (isset($c->snippet->authorDisplayName) ? $c->snippet->authorDisplayName : $c['snippet']['authorDisplayName']);
          $g->comment->replies[$k]['channel'] = (isset($c->snippet->authorChannelUrl) ? $c->snippet->authorChannelUrl : $c['snippet']['authorChannelUrl']);
          $g->comment->replies[$k]['icon'] = (isset($c->snippet->authorProfileImageUrl) ? $c->snippet->authorProfileImageUrl : $c['snippet']['authorProfileImageUrl']);
          $g->comment->replies[$k]['createdTS'] = strtotime((isset($c->snippet->publishedAt) ? $c->snippet->publishedAt : $c['snippet']['publishedAt']));
          $g->comment->replies[$k]['created'] = date('Y年m月d日 H:i:s', strtotime((isset($c->snippet->publishedAt) ? $c->snippet->publishedAt : $c['snippet']['publishedAt'])));
          $g->comment->replies[$k]['message'] = strip_tags((isset($c->snippet->textDisplay) ? $c->snippet->textDisplay : $c['snippet']['textDisplay']), array('<br />'));
        }
      }

      $come['come'][] = $g->comment;
    }

    $come['total'] = $get->pageInfo->totalResults;
    $come['prevPage'] = (isset($get->prevPageToken) ? $get->prevPageToken : '');
    $come['nextPage'] = (isset($get->nextPageToken) ? $get->nextPageToken : '');

    return $come;
  }

  function backupYTComment ($slug, $com) {
    foreach ($com['come'] as $c) {
      $icon = substr($c->icon, 0, strpos($c->icon, "="));
      $icon = str_replace('https://yt3.ggpht.com/', '', $icon).'.jpg';
      $icon = str_replace('ytc/', '', $icon).'.jpg';
      if ($icon != '.jpg') {
        $isicon = array_diff(scandir(dirname(__DIR__, 4).'/storage/app/public/yt_icon'), array('..', '.'));
        if (!in_array($icon, $isicon)) passthru('wget -O '.dirname(__DIR__, 4).'/storage/app/public/yt_icon/'.$icon.' '.$c->icon);
        $c->icon = '/storage/yt_icon/'.$icon;
      }

      if (isset($c->replies)) {
        foreach ($c->replies as $i => $r) {
          $icon = substr($r['icon'], 0, strpos($r['icon'], "="));
          $icon = str_replace('https://yt3.ggpht.com/', '', $icon).'.jpg';
          $icon = str_replace('ytc/', '', $icon).'.jpg';
          if ($icon != '.jpg') {
            $isicon = array_diff(scandir(dirname(__DIR__, 4).'/storage/app/public/yt_icon'), array('..', '.'));
            if (!in_array($icon, $isicon)) passthru('wget -O '.dirname(__DIR__, 4).'/storage/app/public/yt_icon/'.$icon.' '.$r['icon']);
            $c->replies[$i]['icon'] = '/storage/yt_icon/'.$icon;
          }
        }
      }
    }

    if ($chk = DB::table('vid_ytcomment')->where('vid', $slug)->first()) DB::table('vid_ytcomment')->where('vid', $slug)->update(['come' => serialize($com)]);
    else DB::table('vid_ytcomment')->insert(['vid' => $slug, 'come' => serialize($com)]);
    
    return $com;
  }

  function backupPeerComment ($slug, $com) {
    foreach ($com['come'] as $c) {
      $icon = strstr($c->icon, 'avatars/');
      $icon = str_replace('avatars/', '', $icon);
      if ($icon != '.jpg') {
        $isicon = array_diff(scandir(dirname(__DIR__, 4).'/storage/app/public/kero_icon'), array('..', '.'));
        if (!in_array($icon, $isicon)) passthru('wget -O '.dirname(__DIR__, 4).'/storage/app/public/kero_icon/'.$icon.' '.$c->icon);
        $c->icon = '/storage/kero_icon/'.$icon;
      }
    }

    if ($chk = DB::table('vid_kerocomment')->where('vid', $slug)->first()) DB::table('vid_kerocomment')->where('vid', $slug)->update(['come' => serialize($com)]);
    else DB::table('vid_kerocomment')->insert(['vid' => $slug, 'come' => serialize($com)]);
    
    return $com;
  }
}