<?php

class csvUtil {

  function __construct() {
    $this->logger = new logger(basename(__FILE__));
  }

  function __destruct() {
  }

  function insertIMPCSV($dbutil, $wseq, $flg, $tblid, $cnt, $linebuf) {
    global $serverUtil;
    $valueData['wseq'] = $wseq;
    $valueData['flg'] = $flg;
    $valueData['tblid'] = $tblid;
    $valueData['idx'] = $cnt;
    $valueData['csv'] = $linebuf;
    $file = $serverUtil->getProjectDir() . "/util/sql/insertImpcsv.sql";
    $sql = file_get_contents($file);
    $result = $dbutil->insertCsv($sql, $valueData);
    return true;
  }

  public function readCsv($filePath) {

  	// CSV読み込み
  	$file = new SplFileObject($filePath);
  	$file->setFlags(SplFileObject::READ_CSV);

  	$csvList = array();
  	foreach ($file as $line) {
  		// 空のレコードは無視
  		if (!empty($line)) {
  			$csvList[] = $line;
  		}
  	}

  	// 空っぽだったら例外。
  	if (empty($csvList)) {
  		throw new Exception('CSVファイルの中身が空です。');
  	}

  	// 文字コードをコンバートする。
  	mb_convert_variables('UTF-8', 'MS932,SJIS-win,SJIS', $csvList);

  	return $csvList;

  }

  public function createCsv($export_csv_title, $data, $delimiter = ",", $enclosure = '"', $endmarkflg = "0"){
    //$endmarkflg : '0'=\r\n, '1'=\r, '2'=\n
//$this->logger->info("createCsv", $data);
    // ファイル名
    global $serverUtil;
    global $stringUtil;
    $topDir = $serverUtil->getProjectDir();
    $file_path = $topDir . "/dl/" . uniqid(). ".csv";

    if ($endmarkflg == '0') {
      $endmark = "\r\n";
    } else if ($endmarkflg == '1') {
      $endmark = "\r";
    } else if ($endmarkflg == '2') {
      $endmark = "\n";
    } else if ($endmarkflg == '3') {
      $endmark = "";
    }

    if( touch($file_path) ){
      // オブジェクト生成
//      $file = new SplFileObject( $file_path, "w" );
      $createCsvFile = fopen($file_path, "w");
      if ($export_csv_title != null) {  //タイトルがある場合のみ
        // タイトル行のエンコードをSJIS-winに変換（一部環境依存文字に対応用）
        //$this->logger->error("export_csv_title", $export_csv_title);
        $buff = "";
        $i = 0;
        foreach( $export_csv_title as $key => $val ){
          //$this->logger->error("export_header[]", $export_header[]);
          if ($i > 0) {
            $buff .= $delimiter;
          }
          $buff .= $enclosure.mb_convert_encoding($val, 'SJIS-win', 'UTF-8').$enclosure;
          $i++;
        }
        $buff .= $endmark;
        fwrite($createCsvFile,$buff);
      }

      //$this->logger->info("data", $data);
      foreach ($data as $id => $csvData) {
        $i = 0;
        $buff = "";
          //$this->logger->error("val", $csvData);
        foreach ($csvData as $id => $val) {
          if ($i > 0) {
            $buff .= $delimiter;
          }
          $buff .= $enclosure.mb_convert_encoding($val, 'SJIS-win', 'UTF-8').$enclosure;
          $i++;
        }
        $buff .= $endmark;
        fwrite($createCsvFile,$buff);
      }
      fclose($createCsvFile);

    }

    return $file_path;
  }

  public function convertEOL($string, $to = "\n") {
    return preg_replace("/\r\n|\r|\n/", $to, $string);
  }



}

?>
