<?php
/**
 * @copyright ONE/DEPO Project
 * @license   PHP License 3.01 <http://www.php.net/license/3_01.txt>
 */

/**
 * 画像データ一括登録
 *
 * @package     imageimport
 * @author      netnee
 * @access      public
 */
class Onedepo_Logic_Imageimport {

    var $imageimport;
    var $dbaccess;

    var $img_files;
    var $itemdata;

    var $logfile;
    var $tempfile;

    var $img_dir = array(IMAGE_IMPORT_DIR_L,
                         IMAGE_IMPORT_DIR_M,
                         IMAGE_IMPORT_DIR_S);


    function getImageFiles()
    {
        //画像大
        $this->img_files[0] = $this->getDirectoryFile($this->img_dir[0]);
        //画像中
        $this->img_files[1] = $this->getDirectoryFile($this->img_dir[1]);
        //画像小
        $this->img_files[2] = $this->getDirectoryFile($this->img_dir[2]);

        return $this->img_files;
    }

    function getDirectoryfile($dir)
    {
        if (empty($dir)) return false;

        $files = array();
        clearstatcache();
        if (is_dir($dir)) {
            $handle = opendir($dir);
            while (($filename = readdir($handle)) !== false) {
                $full = $dir ."/". $filename;
                if ($filename != "." &&
                    $filename != ".." &&
                    is_file($full)) {

                    $files[] = $filename;
                }
            }
            closedir($handle);
        }
        return $files;
    }

    /*
    function getItemData () {
        $db = $this->dbaccess->doConnect();
        $sql = "select s_get_nocase_text(makeritemcd) as makeritemcd,
                       itemcd
                  from v_item_list";
        $this->itemdata =
          $db->getAssoc($sql, false, array(), DB_FETCHMODE_DEFAULT, true);
        $this->dbaccess->doClose($db);
    }
    */

    function getNoCaseText ($makeritemcd) {
        $s = mb_convert_kana($makeritemcd, "AS", "UTF-8");
        $rep = array("-","ー","―","－");
        $s = mb_strtoupper(str_replace($rep, "‐", $s), "UTF-8");
        return $s;
    }

    function doImport($dt)
    {
        $log =& LogFactory::getLog();

        // 画像ファイル取得
        $this->getImageFiles();

        $updateusrnm = "-imgimp-". $dt;
        $resultmsg = array();
        $row = 0;
        $okrow = 0;
        $ngrow = 0;

        $db = $this->dbaccess->doConnect();
        $db->autoCommit(false);

        foreach($this->img_files as $key => $val) {
            // $key==0 が画像大
            // $key==1 が画像中
            // $key==2 が画像小
            $dir = $this->img_dir[$key];
            switch ($key) {
                case 0:
                $imgsize = 'L';
                break;
                case 1:
                $imgsize = 'M';
                break;
                case 2:
                $imgsize = 'S';
                break;
            }
            $log->debug($dir, "doImport - image_directory");

            foreach($val as $v) {
                if ($row>=IMPORT_MAX) break;

                $error = false;
                $row++;

                $e = explode(".", $v);
                $makeritemcd = $e[0];
                $log->debug($makeritemcd, "doImport - makeritemcd");
                if (empty($makeritemcd)) {
                    $error = true;
                    $resultmsg[] = '品番「'. $makeritemcd .'」がありません';
                    $ngrow++;
                    continue;
                }

                // 画像登録 ロールバック無し
                $db->query('BEGIN;');
                $sql  = "select * from f_image_import(?,1,?,?);";
                $params = array($makeritemcd,
                                $imgsize,
                                $updateusrnm);

                $log->debug($sql, "doImport - sql");
                $log->debug(print_r($params,true), "doImport - params");

                $res = $db->getRow($sql, $params, DB_FETCHMODE_ASSOC);
                if (DB::isError($res) || $res["errcd"] < 0) {
                    if (DB::isError($res)) {
                        $resultmsg[] = "DBエラー\n.....処理を停止します";
                        $log->info("db sintax error [userinfo] = ".
                                   $res->userinfo,
                                   "Onedepo_Logic_Imageimport#doImport");
                        $error = true;
                        $db->query('ROLLBACK;');
                        $ngrow++;
                        break;
                    } else {
                        $resultmsg[] = $res["errmsg"];
                        $log->info("import error [message]=".
                                   $res["errmsg"],
                                   "Onedepo_Logic_Imageimport#doImport");
                    }
                    $error = true;
                    $db->query('ROLLBACK;');
                    $ngrow++;
                    continue;
                } else {
                    $itemcd = $res["errcd"];
                    $okrow++;
                }

                $imp_imgfile  = $dir ."/". $v;
                // 品目Cと紐付けたファイル名でrename
                $imp_newfile  = IMAGE_DIR ."/1/". $itemcd . $imgsize .".jpg";
                $cachefile = IMAGE_CACHEDIR ."/1/". $itemcd . $imgsize .".jpg";

                $log->debug($imp_imgfile, "doImport - imp_imgfile");
                $log->debug($imp_newfile, "doImport - imp_newfile");

                clearstatcache();
                if (is_file($imp_imgfile)) {
                    if (!$error) {
                        if (is_file($imp_newfile)) {
                            chmod($imp_newfile, 0666);
                            unlink($imp_newfile);
                        }
                        //@copy($imp_imgfile,  $imp_newfile);
                        @rename($imp_imgfile,  $imp_newfile);
                        exec("sudo chmod 0666 $imp_newfile");
                        unlink($cachefile);
                    }
                } else {
                    $error = true;
                    $resultmsg[] = "画像が見つかりません ". $imp_imgfile .
                                   "\n.....処理を停止します";
                    $log->info("file not found ".
                               $imp_imgfile,
                               "Onedepo_Logic_Imageimport#doImport");
                    $db->query('ROLLBACK;');
                    $ngrow++;
                    $okrow--;
                    break;
                }
                //--
                $db->query('COMMIT;');
            }
        }

        $this->dbaccess->doClose($db);

        return array("errcd"  => 0,
                     "allrow" => $row,
                     "okrow"  => $okrow,
                     "ngrow"  => $ngrow,
                     "errmsg" => $resultmsg);
    }
}
?>