<?php

class presentSCORM extends presentBase {

  public function onPrivateUpload($fileName) {
    myZip::Unzip($fileName, $this->getViewPath());
    $this->fixVietnamesePath();

    $playerName = $this->present->getPrPlayerName();
    $dirs = explode('/', $playerName);
    $file = array_pop($dirs);
    $baseDir = implode('/', $dirs);

    if ($file == 'breeze-manifest.xml') {
      $this->convertBreezeToScorm($this->getViewPath().$baseDir);
      $playerName = ($baseDir? $baseDir.'/': '').'imsmanifest.xml';
    }

    $newPack = new SCORM13Package();
    $res = $newPack->import($this->present->getPrId(), $this->getViewPath().$playerName, false, true);
    if ($res===false) throw new Exception('Upload bài giảng không thành công');
    array_push($dirs, $res['href']);
    $playerName = implode('/', $dirs);

    $this->present->setPrBaseDir($baseDir);
    $this->present->setPrPlayerName($playerName);
    if ($res['title'] && !$this->present->getPrName()) $this->present->setPrName($res['title']);
    $this->present->setPrStatus(0);
  }

  public function fixVietnamesePath() {
    $dirs = explode('/', $this->present->getPrPlayerName());
    $path = $this->getViewPath();

    for ($i = 0; $i < count($dirs) - 1; $i++) {
      $newDir = preg_replace('@[^A-Za-z0-9_ \-\(\)\.]+@', '_', $dirs[$i]);
      if ($newDir != $dirs[$i]) {
        if (file_exists($path. $newDir)) myUtility::cleanDirectory($path. $newDir);
        rename($path. $dirs[$i], $path. $newDir);
        $dirs[$i] = $newDir;
      }
      $path .= $newDir. '/';
    }
    $this->present->setPrPlayerName(implode('/', $dirs));
  }

  function dirList($path, $prefix = '', $lr = "\n") {
    if (!file_exists($path)) return '';
    $list = '';
    foreach (scandir($path) as $dir) {
      if ($dir == '.' || $dir == '..') continue;
      $dname = $path. '/'. $dir;
      if (is_dir($dname)) $list .= $this->dirList($dname, $prefix, $lr);
      else $list .= "$prefix<file href=\"$dname\"/>$lr";
    }
    return $list;
  }

  public function convertBreezeToScorm($path) {
    $type = file_exists($path.'/presenter.crs')? 'aicc': 'scorm';
    myZip::Unzip(sfConfig::get('sf_web_dir')."/plugins/breeze/$type.zip", $path);

    chdir($path);
    $list = $this->dirList('data', "\t\t\t", "\r\n");
    $data = file_get_contents('imsmanifest.xml');
    $data = str_replace('<DATA_FILE_LIST>', $list, $data);
    file_put_contents('imsmanifest.xml', $data);

    $data = file_get_contents('breeze-manifest.xml');
    $pos = strpos($data, '<file href="presenter.crs"/>');
    if ($pos === false) $pos = strpos($data, '<file href="breeze-manifest.xml"/>');
    if ($pos === false) $pos = strpos($data, '<file href=');

    $str = $this->dirList('scorm2004').
    '<file href="adlcp_rootv1p2.xsd"/>'."\n".
    '<file href="imscp_rootv1p1p2.xsd"/>'."\n".
    '<file href="imsmd_rootv1p2p1.xsd"/>'."\n".
    '<file href="ims_xml.xsd"/>'."\n".
    '<file href="SCORM.htm"/>'."\n".
    $this->dirList('scorm_support');

    $data = substr_replace($data, $str, $pos, 0);
    file_put_contents('breeze-manifest.xml', $data);
  }

  public function onThumbUpload($thumbSrc) {
    parent::onThumbUpload($thumbSrc);
    $thumb2 = $this->getThumbPath().'thumbnail2.jpg';
    if (sfConversion::SizeImage(500, 375, $thumbSrc, $thumb2)) myUtility::track_upload($thumb2, 'thumbnails');
  }

  public function getPreview($width = 500, $height = 375) {
    if ($this->present->getPrThumbnail() == 1) {
      $preview = image_tag($this->getThumbPath(false).'thumbnail2.jpg', array('width'=>$width, 'height'=>$height));
    } else {
      $src = $this->getViewPath(false).$this->present->getPrPlayerName();
      $preview = content_tag('div',
      '<iframe src="'.$src.'" width="'.$width.'" height="'.$height.'" frameborder="0"></iframe>'.
      '<div style="position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.2);"></div>',
      array('style'=>'position:relative'));
    }
    return $preview;
  }

  public function getThumbnail($options = null) {
    if ($this->present->getPrThumbnail() == 1) return parent::getThumbnail($options);
    return image_tag($this->thumbRoot.'uploads/thumbnails/scorm-icon.gif', $options);
  }

  public function getDownloadLink($icon = false) {
    $title = 'Học trực tuyến bài giảng SCORM';
    $name = $icon? image_tag('/images/layout1/learning.png').'&nbsp;': $title;
    $options = $icon? array('title' => $title): array();
    $pr_id = $this->present->getPrId();
    $user = sfContext::getInstance()->getUser();
    if ($user->isAuthenticated() && $this->present->getPrPrice() && $this->present->getUserLicense($user->getUserId())) {
      $base = url_for('/present/playsco', true);
      $options['target'] = '_blank';
      return link_to($name, $base.'/catId/'.$this->present->getPrCategory().'/packageId/'.$pr_id, $options);
    } else {
      return mm_link_need_login($name, '/present/predownload?pr_id='.$pr_id.'&act=view', true, $options);
    }
  }
}
