/*
 * Copyright (c) 2006 Ichro Maruta
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 * */

var option_proc = {
  _db_service_e: null,
  _db_service_j: null,
  _e_record: 0,
  _j_record: 0,
  _stat: null,

  initialize: function () {
    this._db_service_e = Components.classes["@nori090.org/english/sqlite-service;1"].getService(Components.interfaces.modicIEnglishDB);
    this._db_service_j = Components.classes["@nori090.org/japanese/sqlite-service;1"].getService(Components.interfaces.modicIJapaneseDB);
    this._stat = document.getElementById('stat');
    this._db_service_e.executeSimpleSQL("BEGIN TRANSACTION");
    var count_statement = this._db_service_e.createStatement("SELECT COUNT(*) FROM dict");
    try {
      if (count_statement.executeStep()) {
        this._e_record += count_statement.getInt32(0);
      }
    } finally {
      count_statement.reset();
    }
    this._db_service_e.executeSimpleSQL("END TRANSACTION");

    this._db_service_j.executeSimpleSQL("BEGIN TRANSACTION");
    var count_statement = this._db_service_j.createStatement("SELECT COUNT(*) FROM dict");
    try {
      if (count_statement.executeStep()) {
        this._j_record += count_statement.getInt32(0);
      }
    } finally {
      count_statement.reset();
    }
    this._db_service_j.executeSimpleSQL("END TRANSACTION");
 

    if (this._e_record == 0 && this._j_record == 0) {
      this._stat.value = "[辞書のロード]をクリックして，検索の対象となる辞書データを登録してください．\n" + "使用可能なデータはPDICの一行テキスト形式(Shift-JIS)です．\n" + "英辞郎のデータを用いる場合，事前にPDICを用いてデータの形式を変換してください．PDICで出力される場合、Shift-JISへのエンコードが必要です。\n" + "登録には数分を要することがあります．経過はここに表示されます．\n";
    } else {
      this._stat.value = "現在のデータ数(英和)：" + this._e_record + "項目\n" + "現在のデータ数(和英)：" + this._j_record + "項目\n" + "既にデータが登録されている場合は全て上書きします。\n";
    }
  },

  dic_loader: function(aFile,db) {
    this._stat.value = "辞書ファイルを開きました．\n登録を開始します．\n";
    var stat_prev = this._stat.value;
    
    var stream = Components.classes['@mozilla.org/network/file-input-stream;1'].createInstance(Components.interfaces.nsIFileInputStream);
    stream.init(aFile, 1, 0, false);
    var is = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Components.interfaces.nsIConverterInputStream);
    is.init(stream, "Shift-JIS", 1024, 0xFFFD);
    db.executeSimpleSQL("BEGIN TRANSACTION");
    var statement = db.createStatement("INSERT INTO dict VALUES (?1,?2)");
    if (is instanceof Components.interfaces.nsIUnicharLineInputStream) {
      this.temp_proc = {
        do:function(){
          var i = 0;
          var line = {};
          var temp = [];
          for (i = 0; i < 1000; i++) {
            if (!option_proc.temp_proc.is.readLine(line)) {
              option_proc.temp_proc.count+=i;
              option_proc._stat.value = option_proc.temp_proc.stat_prev + option_proc.temp_proc.count + "個のデータを登録しました．";
              option_proc.temp_proc.statement.reset();
              option_proc.temp_proc.is.close();
              option_proc.temp_proc.stream.close();
              option_proc.temp_proc.db.executeSimpleSQL("END TRANSACTION");
              alert('辞書データの登録が完了しました．');
              window.close();
              return;
            }
            temp = line.value.split(" /// ");
            option_proc.temp_proc.statement.bindUTF8StringParameter(0, temp[0]);
            option_proc.temp_proc.statement.bindUTF8StringParameter(1, temp[1]);
            option_proc.temp_proc.statement.execute();
          }
          option_proc.temp_proc.count+=i;
          option_proc._stat.value = stat_prev + option_proc.temp_proc.count + "個のデータを登録しました．";
          setTimeout('option_proc.temp_proc.do();' ,10);
        },
        db:db,
        is:is,
        count:0,
        stream:stream,
        statement:statement,
        stat_prev:stat_prev,
      };
      this.temp_proc.do();
    }
  },
  
  temp_proc : {},

  loaddic: function (db,count) {
    var nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, "辞書ファイルの選択", nsIFilePicker.modeOpen);
    fp.appendFilter("PDIC１行テキスト形式", "*.txt");
    var res = fp.show();
    if (res == nsIFilePicker.returnOK) {
      document.getElementById('load1').disabled=false;
      document.getElementById('load2').disabled=false;
      if (count) {
        db.truncateTable();
      }
      this.dic_loader(fp.file,db);
    }
  },

  loaddic1: function () {
    this.loaddic(this._db_service_e,this._e_record);
  },

  loaddic2: function () {
    this.loaddic(this._db_service_j,this._j_record);
  },

}
