#!/usr/bin/perl

use strict;
use warnings;
use utf8;
use XML::XPath;
use CGI;

use File::Basename;
use File::Spec;
my $dir = dirname( $ENV{'SCRIPT_FILENAME'} );
my $path = File::Spec->catfile( $dir, 'mva-transcript.pl' );
require $path;
$path = File::Spec->catfile( $dir, 'mva-translation.pl' );
require $path;

#require 'mva-transcript.pl';
#require 'mva-translation.pl';

binmode STDOUT, ":utf8";

my $cgi = new CGI;
print $cgi->header(-charset=>"utf-8");

my $title = "MVA Translation";

if($cgi->param('action') eq "play"){
  my $videoDirectory = $cgi->param('videoDirectory');
  &displayVideo($videoDirectory);
  exit;
}

&print_index($cgi);
my $store = "store";
&print_video_list($store);

if(defined($cgi->param('mva_url'))){
  my $url = $cgi->param('mva_url');
  my $outputDirectory = MVA::Transcript::do($url);
  MVA::Translation::do($outputDirectory);
}

sub print_index($){
  my $cgi = shift;
  print <<"_HTML_";
<!DOCTYPE html>
<html class="no-js">
  <head>
    <meta charset='utf-8' />
    <link href="css/accordion.css" media="screen, projection" rel="stylesheet" type="text/css">
    <link href="css/table.css" media="screen, projection" rel="stylesheet" type="text/css">
    <title>Developers Convention - $title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Captionator/0.6/js/captionator-min.js" type="text/javascript"></script>
    <script type="text/javascript">
      window.addEventListener("load",function(eventData) {
        captionator.captionify();
      });
    </script>
  </head>
  <body style="margin: 0; padding: 0;">
  <div id="site_bar" style="margin: 0px auto; background: #E00; color: #FFF;padding: 2px 15px 2px 15px;">
    <center>
    <a href="/dc"><img src="../img/DevelopersConvention.png" /></a>
    </center>
    <a href="/dc/mva" style="color: #FFF;">MVA Translation</a>
    &nbsp;
    <a href="/dc/naming" style="color: #FFF;">Naming</a>
    &nbsp;
    <a href="/dc/as" style="color: #FFF;">Association Search</a>
    &nbsp;
    <a href="/dc/cs" style="color: #FFF;">Code Snippet</a>
    &nbsp;
    <a href="/dc/db" style="color: #FFF;">DB</a>
    &nbsp;
    <a href="/dc/my-mind" style="color: #FFF;">My Mind Map</a>
    &nbsp;
    <a href="/dc/wiki" style="color: #FFF;">Wiki</a>
  </div>

  <!--
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <path stroke="#000" stroke-width="2" fill="none" d="M 818 110 C 836 110 836 182 854 182"></path>
  </svg>
  -->
  <div align="center" class="search_form">
    <div class="search_title">
      <h2>
        <img src="/favicon.ico" width="40" height="40" />
        $title
      </h2>
    </div>

      <p>
      e.g.) 
      <span style="color: green;">
      https://mva.microsoft.com/en-US/training-courses/introduction-to-net-core-16764
      </span>
      </p>

    <form action="./" method="POST" name="f" class="search_form">
      <p>MVA URL:<input type="text" size="100" name="mva_url" id="mva_url"/></p>
      <input type="submit" value="Request Translation" />
    </form>
  </div>
  <br />
_HTML_

}

sub print_video_list($){
  my $store = shift;
  opendir(my $dh, $store) or die "can't opendir $store$!";
  my @courceList = grep !/^\./, readdir $dh;
  closedir $dh;
     
  my %courceSorted;
  foreach my $cource (@courceList){
    my $mtime = (stat("$store/$cource"))[9];
    push @{$courceSorted{$mtime}},$cource;
  }

  print '<section class="ac-container">';
  my $courceCount = 1;
  foreach my $time (sort {$b <=> $a} keys %courceSorted){
    foreach my $cource (@{$courceSorted{$time}}){
      print '<div>';
      if($courceCount == 1){
        print '<input id="ac-' . $courceCount . '" name="accordion-1" type="radio" checked>';
      } else {
        print '<input id="ac-' . $courceCount . '" name="accordion-1" type="radio">';
      }
      print '<label for="ac-' . $courceCount . '">' . $cource . '</label>';
      print '<article><p>';
      opendir(my $cdh, $store."/".$cource) or die "can't opendir $store/$cource$!";
      my @categoryList = grep !/^\./, readdir $cdh;
      @categoryList = sort { (split(/_/,$a))[0] <=> (split(/_/,$b))[0] } @categoryList;
      closedir $cdh;

      foreach my $category(@categoryList){
        opendir(my $vdh, $store."/".$cource."/".$category) or die "can't opendir $store/$cource/$category$!";
        my @videoList = grep !/^\./, readdir $vdh;
        closedir $vdh;
        print '' . $category . '';
        print '<table cellspacing="0">';
        print '  <thead>';
        print '    <tr>';
        print '      <th>Name</th>';
        print '      <th>Play</th>';
        print '      <th>Video(360p)</th>';
        print '      <th>Video(540p)</th>';
        print '      <th>Video(720p)</th>';
        print '      <th>TTML(en)</th>';
        print '      <th>WebVTT(en)</th>';
        print '      <th>WebVTT(ja)</th>';
        print '    </tr>';
	      print '  </thead>';
	      print '  <tbody>';
        foreach my $video(sort(@videoList)){
          my $videoDirectory = $store."/".$cource."/".$category."/".$video;
          my $videoSettings = $videoDirectory."/"."videosettings.xml";
          my $videoCc = $videoDirectory."/"."video_cc.xml";
          my $videoCcEn = $videoDirectory."/"."video_cc.en.vtt";
          my $videoCcJa = $videoDirectory."/"."video_cc.ja.vtt";

          print '    <tr>';
          print '      <td>' . $video . '</td>';

          my $xp = XML::XPath->new(filename=>$videoSettings);
          my $item = $xp->find('//videoSettings/PlaylistItems/PlaylistItem/MediaSources[@videoType="progressive"]');
          print '      <td>';
          if($item->size() != 0){
            print '<a href="?action=play&videoDirectory=' . $videoDirectory . '" target="_blank"><img src="images/play.png"/></a>';
          }
          print '      </td>';

          my $items = $xp->findnodes('//videoSettings/PlaylistItems/PlaylistItem/MediaSources[@videoType="progressive"]/MediaSource');
          if (@$items == 0){
            print '      <td>';
            print '      </td>';
            print '      <td>';
            print '      </td>';
            print '      <td>';
            print '      </td>';
          }
          foreach my $item ( @$items ){
            # 720p 540p 360p
            print '      <td>';
            print '<a href="' . $item->string_value() . '">';
            print '<img src="images/film.png" />';
            print '</a>';
            print '      </td>';
          }

          print '      <td>';
          print '<a href="' . $videoCc . '">';
          print '<img src="images/cc.png" />';
          print '</a>';
          print '      </td>';

          print '      <td>';
          print '<a href="' . $videoCcEn . '">';
          print '<img src="images/cc.png" />';
          print '</a>';
          print '      </td>';

          print '      <td>';
          if(-e $videoCcJa){
            print '<a href="' . $videoCcJa . '">';
            print '<img src="images/cc.png" />';
            print '</a>';
          } else {
            print 'Now translating...';
            print '<img src="images/loading.gif"/>';
          }
          print '      </td>';
          print '    </tr>';
        }
        print '  </tbody>';
        print '</table>';
      }
      print '</p></article>';
      print '</div>';
    }
    $courceCount++;
  }
  print '</section>';
}

sub displayVideo($){
  my $videoDirectory = shift;
  my $xp = XML::XPath->new(filename=>$videoDirectory."/videosettings.xml");
  my $item = $xp->find('//videoSettings/PlaylistItems/PlaylistItem/MediaSources[@videoType="progressive"]/MediaSource[@videoMode="360p"]');
  my $videoUrl = $item->string_value();

  print <<"_HTML_";
  <video controls preload="auto" width="640" height="360">
    <source src="$videoUrl" type="video/mp4">
    <track src="$videoDirectory/video_cc.ja.vtt" kind="captions" srclang="ja" default>
    <track src="$videoDirectory/video_cc.en.vtt" kind="captions" srclang="en">
    <p>このブラウザは動画再生に対応していません</p>
  </video>
_HTML_
}
