<?php

class userBase {

  const MAX_PLUS_POINT = 30;

  protected $user;

  public function userBase($user) {
    $this->user = $user;
  }

  public function getTitle() {
    return '';
  }

  public function getAvatar($type = 'avatar', $options = array()) {
    $avatar = $this->user->getUsAvatar();
    if (strpos($avatar, ':') !== false) {
      $avatars = unserialize($avatar);
      $avatar = $avatars[($type=='avatar'? 0: 1)][0];
    }
    if ($avatar == null) {
      $mf = ($this->user->getUsSex()==2? 'f': '');
      $avatar = "no_$type$mf.jpg";
    }
    return image_tag(sfConfig::get('app_thumbnail_root').$this->getAvatarPath($type, false).$avatar, $options);
  }

  public function getHtmlName($avatar = false, $homepage = false) {
    if ($this->user->getUsId() == null) return "Không rõ";
    $html = '';
    $link = '/user/show?id='.$this->user->getUsId();
    if ($avatar) {
      $avalink = link_to($this->getAvatar('avatar', array('style'=>'float:left', 'width'=>'30px', 'height'=>30)), $link);
      $html .= content_tag('div', $avalink, array('class'=>'ava'));
    }
    $html .= link_to($this->user->getUsFullname(), $link);
    if ($homepage) {
        $url = $this->user->getUsHomepage();
        if ($url) $html .= ' ('.link_to('trang riêng', $url).')';
    }
    return $html;
  }

  public function getAvatarPath($type = 'avatar', $absolute = true) {
    return sfConfig::get($absolute? 'sf_upload_dir': 'sf_upload_dir_name')."/thumbnails/$type/";
  }

  public function SaveAvatar($action) {
    $us_id = $this->user->getUsId();
    $avatar = $us_id.'.jpg';
    $this->user->setUsAvatar($avatar);
    $fileName1 = $this->getAvatarPath('avatar').$avatar;
    $fileName2 = $this->getAvatarPath('photo').$avatar;

    $tempFile = $action->getRequest()->CopyTempFile($action->uploaded, "user_{$us_id}_picture.jpg");
    list($width, $height) = @getimagesize($tempFile);
    if ($width/$height < 163/187) myUtility::SizeImage(150, 200, $tempFile, $fileName2);
    else if ($width/$height > 187/163) myUtility::SizeImage(200, 150, $tempFile, $fileName2);
    else myUtility::SizeImage(175, 175, $tempFile, $fileName2);
    myUtility::SizeImage(60, 60, $tempFile, $fileName1);
    myUtility::track_upload($fileName1, 'thumbnails');
    myUtility::track_upload($fileName2, 'thumbnails');
    unlink($tempFile);
  }

  public function checkUserLock() {
    /*
    if (sfContext::getInstance()->getRequest()->getCookie('vol_lock')==1) {
      throw new Exception('Máy tính này đã bị khóa truy cập');
    }
    */

    // Check whether user can signIn or not
    switch ($this->user->getUsStatus()) {
      case 4:
      case 5:
      case 6:
      case 7:
        if (strtotime($this->user->getUsLastvisited()) > time()) {
          throw new Exception('Tài khoản này bị khóa đến '.$this->user->getUsLastvisited('H:i d-m-Y'));
        }
        else $this->user->setUsStatus($this->user->getUsStatus() - 4);
        break;
      case 8:
        sfContext::getInstance()->getResponse()->setCookie('vol_lock', 1, time() + 86400*5);
        throw new Exception('Tài khoản này đã bị khóa vĩnh viễn');
        break;
    }

    sfDatabaseSessionStorage::kickUserByName($this->user->getUsUsername());
  }

  public function onLogin() {
    // cộng điểm trong lần đăng nhập đầu tiên của tuần
    $lastvisited = $this->user->getUsLastvisited();
    if ($lastvisited != null && date("W", strtotime($lastvisited)) != date("W")) {
      $maxPlus = self::MAX_PLUS_POINT;
      $download = explode(',', $this->user->getUsDownload());
      $plus = min(intval($download[0]), $maxPlus);
      $plus = max($plus, $maxPlus - $this->user->getUsScore());
      $this->user->setUsPointPlus($this->user->getUsPointPlus() + $plus);
      $this->user->setUsScore($this->user->getUsScore() + $plus);
      $download[0] = 0;
      $this->user->setUsDownload(implode(',', $download));
    }

    $this->user->setUsLastvisited(date('Y-m-d H:i:s'));
    $this->user->save();
    myUtility::log('['.$this->user->getUsId().']: '.myUtility::getRealIpAddr(), 'login.log');
  }

  public static function getUserObject($user) {
    $tblcheckinfo = $user->getTblblogcheckinfo();
    if (!$tblcheckinfo) return new userBase($user);

    $position = $tblcheckinfo->getCiPosition();
    if ($position < 40) return new userTeacher($user);
    else return new userBase($user);
  }
}
