using System; using System.Collections.Generic; using System.Linq; using System.Text; using TimeKeeper.Models.Types; namespace TimeKeeper.Database { public class TDatabase : DatabaseDriver, IDisposable { private static TDatabase instance; private TDatabase() : base(StaticConfig.DbConfig.Engine, StaticConfig.DbConfig.Host, StaticConfig.DbConfig.Port, StaticConfig.DbConfig.Db, StaticConfig.DbConfig.User, StaticConfig.DbConfig.Pass, new DatabaseEngine[] { DatabaseEngine.Mysql}) { // Try and Reconnect try { Connect(); // Try to get the database version try { if(base.Query("SELECT dbver FROM _version LIMIT 1").Count == 0) throw new Exception(); } catch { base.Execute(Utils.GetResourceAsString("TimeKeeper.Database.SQL.MySQL.Install.sql")); } } catch(Exception) { if(Connection != null) Connection.Dispose(); throw; } } public static TDatabase getInstance() { if(instance == null) { instance = new TDatabase(); } return instance; } ~TDatabase() { if(!IsDisposed) base.Dispose(); } internal void addWorking(WorkMessage m) { List> dayItems = this.getWorkOnDay(m.time); if(dayItems.Count == 0 && m.working == 1) { this.insertStartWork(m.time, m.jobID); } else if(dayItems.Count > 0) { int started = -1; int job = -1; foreach(Dictionary dayItem in dayItems) { if((TimeSpan)dayItem["stop"] == TimeSpan.Zero) { started = (int)dayItem["id"]; job = (int)dayItem["location"]; break; } } if(started != -1 && m.working == 0 && m.jobID == job) { this.updateStopWorking(started, m.time); } else if(started == -1 && m.working == 1) { this.insertStartWork(m.time, m.jobID); } else { throw new NotImplementedException(); } } else { throw new NotImplementedException(); } } private void updateStopWorking(Int32 started, DateTime time) { base.Execute("UPDATE `work` SET stop=@P0 WHERE id=@P1", time.ToString("HH:mm:ss"), started.ToString()); } internal bool insertStartWork(DateTime time, Int32 jobID) { int Rows = base.Execute("INSERT INTO `work` (`date`, `start`, `type`, `location`) VALUES (@P0, @P1, @P2, @P3)", time.ToString("yyyy-MM-dd"), time.ToString("HH:mm:ss"), "ok", jobID.ToString() ); return (Rows != 0); } internal List> getWorkOnDay(DateTime time) { return base.Query("SELECT * FROM `work` WHERE date=@P0 ORDER BY `start` ASC", time.ToString("yyyy-MM-dd")); } /// /// Returns the number of accounts in the database /// /// public int GetNumAccounts() { var Row = base.Query("SELECT COUNT(id) AS count FROM accounts"); return Int32.Parse(Row[0]["count"].ToString()); } } }