<?php

/**
 * Subclass for representing a row from the 'tbluser' table.
 *
 *
 *
 * @package lib.model
 */
class Tbluser extends BaseTbluser {

  private $oldUsername = null;
  protected $userObj = null;

  public function getObject() {
    if ($this->userObj == null) $this->userObj = userBase::getUserObject($this);
    return $this->userObj;
  }

  public function setUsUsername($v) {
    if ($this->oldUsername==null) $this->oldUsername = $this->getUsUsername();
    parent::setUsUsername($v);
  }

  public function save(PropelPDO $con = null) {
    $create = $this->getUsId()==null;

    // update infor in tblbloguser
    if ($this->isColumnModified(TbluserPeer::US_USERNAME)) {
      $c = new Criteria();
      $c->add(TblbloguserPeer::US_USER, $this->getUsId());
      $tblblogusers = TblbloguserPeer::doSelect($c);
      foreach ($tblblogusers as $tblbloguser) {
        $tblbloguser->setUsNickname($this->getUsUsername());
        $tblbloguser->save();
      }
      $c = new Criteria();
      $c->add(TblblogPeer::BL_USER, $this->getUsId());
      $c->add(TblblogPeer::BL_SHORTNAME, $this->oldUsername);
      $c->add(TblblogPeer::BL_TYPE, 1);
      $tblblog = TblblogPeer::doSelectOne($c);
      if ($tblblog) {
        $tblblog->setBlShortname($this->getUsUsername());
        $tblblog->save();
      }
    }
    if ($this->isColumnModified(TbluserPeer::US_LASTNAME) || $this->isColumnModified(TbluserPeer::US_FIRSTNAME)) {
      $val = new Criteria();
      $val->add(TblbloguserPeer::US_FULLNAME, $this->getUsFullName());
      $c = new Criteria();
      $c->add(TblbloguserPeer::US_USER, $this->getUsId());
      BasePeer::doUpdate($c, $val, Propel::getConnection(TblbloguserPeer::DATABASE_NAME));
    }
    if ($this->isColumnModified(TbluserPeer::US_SCORE)) {
      $val = new Criteria();
      $val->add(TblblogcheckinfoPeer::CI_SCORE, $this->getUsScore());
      $c = new Criteria();
      $c->add(TblblogcheckinfoPeer::CI_USERID, $this->getUsId());
      BasePeer::doUpdate($c, $val, Propel::getConnection(TblblogcheckinfoPeer::DATABASE_NAME));
    }

    parent::save($con);
    if ($create) {
      $this->setUsIdmd5(md5($this->getUsId()));
      parent::save($con);
    }
  }

  /**
   *
   * @return full name of user
   */
  public function getUsFullname() {
    if ($this->getUsStatus()<10) {
      if (null==$this->getUsLastname() && null==$this->getUsFirstname())
		  return '';
        /*return $this->getUsUsername();*/
      else
        return $this->getUsLastname().' '.$this->getUsFirstname();
    } else {
      return 'Đang bị khóa';
    }
  }

  public function setUsFullname($fullname) {
    $names = split(' ', $fullname);
    $firstname = array_pop($names);
    $lastname = join($names, ' ');
    $this->setUsFirstname($firstname);
    $this->setUsLastname($lastname);
  }

  public function getUsHomePage() {
  	$homePage = parent::getUsHomepage();
  	if ($homePage === null) {
      $c = new Criteria();
      $c->add(TblblogPeer::BL_USER, $this->getUsId());
      $c->add(TblblogPeer::BL_TYPE, 1);
      $tblblog = TblblogPeer::doSelectOne($c);
      if (!$tblblog) $homePage = '';
      else {
        $homePage = $tblblog->getRootUrl();
        if (preg_match('@^http://(.+)/@', $homePage, $match)) $homePage = $match[1];
      }
      $this->setUsHomepage($homePage);
      $this->save();
    }
    if ($homePage != '') $homePage = 'http://'.$homePage;
  	return $homePage;
  }

  public function getUsKey() {
    $key = parent::getUsKey();
    if ($key == null) {
      $key = rand(1, time());
      $this->setUsKey($key);
      $this->save();
    }
    return $key;
  }

  public function getEmailConfirm() {
    return (parent::getUsStatus() >> 0) & 1;
  }
  public function getMobileConfirm() {
    return (parent::getUsStatus() >> 1) & 1;
  }
  public function setEmailConfirm($v) {
    parent::setUsStatus(parent::getUsStatus() & ~(1 << 0) | ($v << 0));
  }
  public function setMobileConfirm($v) {
    parent::setUsStatus(parent::getUsStatus() & ~(1 << 1) | ($v << 1));
  }

  /**
   *
   * @return number of presentation which is downloaded by user
   */
  public function getDownloadPresentationCount() {
    $c = new Criteria();
    $c->add(TbluserpresentationPeer::USPRE_USER, $this->getUsId());
    return TbluserpresentationPeer::doCount($c);
  }

  /**
   *
   * @return number of document which is downloaded by user
   */
  public function getDownloadDocumentCount() {
    $c = new Criteria();
    $c->add(TbluserdocumentPeer::USDOC_USER, $this->getUsId());
    return TbluserdocumentPeer::doCount($c);
  }

  /**
   *
   * @return number of presentation which is uploaded by user
   */
  public function getUploadPresentationCount() {
    $c = new Criteria();
    $c->add(TblpresentationPeer::PR_USER, $this->getUsId());
    $c->add(TblpresentationPeer::PR_STATUS, array(0,1,100,101), Criteria::IN);
    return TblpresentationPeer::doCount($c);
  }

  /**
   *
   * @return number of document which is uploaded by user
   */
  public function getUploadDocumentCount() {
    $c = new Criteria();
    $c->add(TbldocumentPeer::DOC_USER, $this->getUsId());
    $c->add(TbldocumentPeer::DOC_STATUS, array(0,1,100,101), Criteria::IN);
    return TbldocumentPeer::doCount($c);
  }

  //diem upload bai giang
  public function getUploadPresentationsPoint() {
    $c = new Criteria();
    $c->add(TblpresentationPeer::PR_USER, $this->getUsId());
    $c->add(TblpresentationPeer::PR_STATUS, array(0,1,100,101), Criteria::IN);
    $c->addSelectColumn('sum(pr_hit)');
    $rs = TblpresentationPeer::doSelectStmt($c);
    $row = $rs->fetch(PDO::FETCH_NUM);
    $rs->closeCursor();
    return (int)$row[0];
  }

  //diem upload tu lieu
  public function getUploadDocumentsPoint() {
    $c = new Criteria();
    $c->add(TbldocumentPeer::DOC_USER, $this->getUsId());
    $c->add(TbldocumentPeer::DOC_STATUS, array(0,1,100,101), Criteria::IN);
    $c->addSelectColumn('sum(doc_hit)');
    $rs = TbldocumentPeer::doSelectStmt($c);
    $row = $rs->fetch(PDO::FETCH_NUM);
    $rs->closeCursor();
    return (int)$row[0];
  }

  //diem download (bai giang, ko tinh tu lieu)
  public function getDownloadPresentationsPoint() {
    $c = new Criteria();
    $c->add(TbluserpresentationPeer::USPRE_USER, $this->getUsId());
    $down_pre = TbluserpresentationPeer::doCount($c);
    return $down_pre;
  }

  //tong diem cua thanh vien
  public function getUserPoint() {
    $up_pre = $this->getUploadPresentationsPoint();
    $up_doc = $this->getUploadDocumentsPoint();
    $down_pre = $this->getDownloadPresentationsPoint();

    $score = 80 + $this->getUsPointplus() + $up_pre*3 + $up_doc*1 - $down_pre*1;
    if ($score != $this->getUsScore()) {
      $this->setUsScore($score);
      $this->save();
    }
    return $score;
  }

  public function incDownload($save = true, $incWeekScore = 0) {
    $download = explode(',', $this->getUsDownload());
    if (isset($download[1])) $download[1] = intval($download[1]) + 1;
    if ($incWeekScore != 0)  $download[0] = intval($download[0]) + $incWeekScore;
    $this->setUsDownload(implode(',', $download));
    if ($save) $this->save();
  }

  public function incUpload($save = true) {
    $download = explode(',', $this->getUsDownload());
    if (!isset($download[2])) return;
    $download[2] = intval($download[2]) + 1;
    $this->setUsDownload(implode(',', $download));
    if ($save) $this->save();
  }

  public function getUsUpDown() {
    $download = explode(',', $this->getUsDownload());
    if (!isset($download[1]) || !isset($download[2])) {
      $download[1] = $this->getDownloadPresentationCount() + $this->getDownloadDocumentCount();
      $download[2] = $this->getUploadPresentationCount() + $this->getUploadDocumentCount();
      $this->setUsDownload(implode(',', $download));
      $this->save();
    }
    return $download;
  }

  public function doTransaction($amount, $type, $content) {
    $money = $this->getUsMoney() + $amount;
    if ($money < 0) throw new sfError404Exception('Tài khoản không còn đủ '.myUtility::formatCurrency(-$amount));
    $this->setUsMoney($money);
    $this->save();

    $tbltran = new Tblusertransaction();
    $tbltran->setTrUser($this->getUsId());
    $tbltran->setTrMoney($amount);
    $tbltran->setTrDate(date('Y-m-d H:i:s'));
    $tbltran->setTrType($type);
    $tbltran->setTrContent($content);
    $tbltran->setTrUserip(myUtility::getRealIpAddr());
    $tbltran->save();
  }

  public function getTblblogcheckinfo() {
    $tblblogcheckinfo = parent::getTblblogcheckinfo();
    if (!$tblblogcheckinfo) {
      $tblblogcheckinfo = new Tblblogcheckinfo();
      $tblblogcheckinfo->setCiUserid($this->getUsId());
    }
    return $tblblogcheckinfo;
  }

  public function getPositionTitle() {
    $pos = $this->getTblblogcheckinfo()->getCiPosition();
    if ($pos != null) return blogStore::$position[$pos];
    return '';
  }

  public function getSchoolName($getNameMethod = 'getScName') {
    $school_id = $this->getTblblogcheckinfo()->getCiSchool();
    if ($school_id != null) {
      $school = TblblogschoolsPeer::retrieveByPK($school_id);
      if ($school) return $school->$getNameMethod();
    }
    return $this->getUsSchool();
  }

  public function getDistrictName($getNameMethod = 'getScName') {
    $district_id = $this->getTblblogcheckinfo()->getCiDistrict();
    if ($district_id != null) {
      $district = TblblogschoolsPeer::retrieveByPK($district_id);
      if ($district) return $district->$getNameMethod();
    }
    return '';
  }

  public function getProvinceName($getNameMethod = 'getScName') {
    $province_id = $this->getTblblogcheckinfo()->getCiProvince();
    if ($province_id != null) {
      $province = TblblogschoolsPeer::retrieveByPK($province_id);
      if ($province) return $province->$getNameMethod();
    }
    return $this->getUsProvince();
  }

  public function getCheckerList() {
    $c = new Criteria();
    $c->add(TblblogusercheckPeer::UC_USER, $this->getUsId());
    $c->add(TblblogusercheckPeer::UC_APPROVE, 1);
    $c->setLimit(2);
    $usercheckers = TblblogusercheckPeer::doSelect($c);
    $tblcheckers = array();
    foreach ($usercheckers as $checker) {
      $tblcheckers[] = TbluserPeer::retrieveByPK($checker->getUcChecker());
    }
    return $tblcheckers;
  }
}
