package jp.ac.kyutech.mns.ist;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;

import javax.swing.JOptionPane;

import jp.ac.kyutech.mns.ist.util.FileReadWriter;
import jp.ac.kyutech.mns.ist.util.MyAction;
/**
 * 講義（Lecture）モデル
 * @author miuramo
 *
 */

public class DB_Lecture implements Runnable {
	public int id;
	public int dataamount;
	public String tstamp;
	public String name = "(新規取り込み)";
	public long lastNoteID = 0;//最後に読み込んだID
	boolean hasLastUpdatedNote = false;
	SimpleATN satn;

	Thread reload_thread;//5秒ごとにリロードするためのスレッド

	public DB_Lecture(int _id, int _amount, String _tstamp, SimpleATN _satn) {
		id = _id;
		dataamount = _amount;
		if (dataamount > 0) name = "(継続取り込み)";
		tstamp = _tstamp;
		satn = _satn;
	}
	public String toString(){
		return new String("["+id+"] "+name+" (size: "+dataamount+" "+tstamp+")");
	}
	public void setName(String n){
		name = n;
		if (name==null) name="（名前なし）";
	}

	//ペンデータ読み込み．本当はSimpleATNにかいてもよかったが，長くなりそうなのでここに
	public void loadPenData(SimpleATN satn, ATN_Mysql_DB mysqldb){
		loadPenData(satn, mysqldb, lastNoteID);
		
		if (reload_thread == null){
			reload_thread = new Thread(this);
			reload_thread.start();
		}
		
		//TODO: 読み込み時に，統計情報を計算してしまう．exportTeineiみたいに．
//		ConfigWindow.configWin.draw.outputteinei();
	}
	public void loadPenData(SimpleATN satn, ATN_Mysql_DB mysqldb, long afterTheID){
		ResultSet rs;
		if (id ==0) rs = mysqldb.query("SELECT * from note where (lectureID "+ATN_Mysql_DB.nullorzero_with_is+") and (notid > "+afterTheID+");");
		else  rs = mysqldb.query("SELECT * from note where (lectureID = "+id+") and (notid > "+afterTheID+") order by gentime;");
		try {
			if (ShortStroke.doAssess) {
				FileReadWriter.bufclear();//筆記統計情報を蓄える前にクリア
				FileReadWriter.buffer.add("id, gentime, sbackid, penid, paperid, count, len, avg, var, max, timediff,timed,numchoten,sumangle,avgangle,varangle");//TODO:
			}
			Hashtable<Integer,ShortStroke> pre = new Hashtable<Integer, ShortStroke>();//penid => previous
			while(rs.next()){
				ShortStroke ss = new ShortStroke();
				ss.id = rs.getLong("notid");
				//build xy as sx,sy
				byte[] xy = rs.getBytes("xy");
				float[] sx, sy;
				ByteArrayInputStream bais = new ByteArrayInputStream(xy);
				DataInputStream ois = new DataInputStream(bais);
				int c;
				try {
					c = ois.readInt();
					sx = new float[c]; sy = new float[c];
					for (int i = 0; i < c; i++) sx[i] = ois.readFloat();
					for (int i = 0; i < c; i++) sy[i] = ois.readFloat();
					ss.sx = sx;
					ss.sy = sy;
				} catch (IOException e) {
					e.printStackTrace();
				}
				// end build xy
				ss.color = rs.getInt("pencolor");
				ss.width = rs.getFloat("penwidth");
				ss.time = rs.getLong("gentime");
				ss.penid = rs.getInt("penID");
				ss.paperid = rs.getInt("paperID");
				ss.sbackid = rs.getInt("sbackid");
				ss.setPreviousSS(pre.get(ss.penid));
				pre.put(ss.penid, ss);

				//TODO: 排除
//				if (ss.penid > 10) continue;
//				if (ss.paperid > 2) continue;
				//TODO: ここで不要なペンを読まない，不要な紙を読まない処理
				Note n = satn.getNote(ss.penid);
				n.addStroke(ss);

				if (ss.id > lastNoteID) lastNoteID = ss.id;
				hasLastUpdatedNote = true;
			}
			if (ShortStroke.doAssess) FileReadWriter.bufSave("lec"+id+"_stat.csv");
			
			for(Note n: satn.notes.values()) n.applySheetVisible();
			satn.applyLandscapeMode();
			satn.relayout(1000, "DB_Lec.loadPenData");
//			int zl = satn.getZoomLevel();
//			System.out.println("zoomLevel = "+zl);
			if (hasLastUpdatedNote && SimpleATN.theapp.menutoolbar.getAction("ReLayoutOnNew").isSelected()) {
				satn.zoomToBounds(satn.tempAfterLayoutBounds, 1000, "DB_Lec.loadPenData");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		while(reload_thread != null){
			MyAction act = satn.menutoolbar.getAction("Reload");
			if (act != null && act.isEnabled() && act.isSelected()){
				loadPenData(satn, satn.mysqldb);
//				System.out.println("Auto-Reloaded.");
				if (hasLastUpdatedNote) {
					satn.canvas.repaint();
					hasLastUpdatedNote = false;
				}
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	//自動読み込みをストップする
	public void stop() {
		reload_thread = null;
	}
	public void action(String act){
		if (act.equals("dblclick")){
			if (id != 0) {
				String name = JOptionPane.showInputDialog(satn, "講義名を変更\nInput Lecture Name", this.name);
				if (name != null) {
					satn.mysqldb.renameLecture(id, name);
					this.name = name;
				}
			}
		}
	}
}
