﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cox.Communication.TCP;

namespace Cox
{
	namespace RFID
	{
		class Tag
		{
			string ID;
			public Tag (string ID)
			{
				this.ID = ID;
			}
			~Tag ()
			{
				Dispose ();
			}
			protected void Dispose (bool flag)
			{
				if (flag) {
					ID = null;
				}
			}
			public void Dispose ()
			{
				Dispose (true);
			}
		}
		class BufferData
		{
			Tag mytag;
			DateTime seen;
			DateTime read;
			public BufferData (Tag Tag, DateTime Read)
			{
				this.seen = DateTime.Now;
				this.mytag = Tag;
				this.read = Read;
			}
			~BufferData ()
			{
				Dispose ();
			}
			protected void Dispose (bool flag)
			{
				if (flag) {
					mytag.Dispose ();
					mytag = null;
				}
			}
			public void Dispose ()
			{
				Dispose (true);
			}
		}
		public class Reader
		{
			public Server myserver;
			public string id;
			private List<BufferData> buffer;
			private Log.TextFile logger;
			public delegate void BufferChange (int count, string id);
			public event BufferChange bufferchange;
			public Reader (int port, string id)
			{
				this.myserver = new Server (port);
				this.myserver.receiveddata += new Server.ReceivedData (HandleIncommingData);
				this.myserver.receiveddatarequest += new Server.ReceivedDataRequest (HandleIncommingRequest);
				this.id = id;
				this.buffer = new List<BufferData> ();
				logger = new Log.TextFile ("reader_" + id.Replace ("/", "").Replace ("\\", "").Replace ("=", "").Replace ("+", "") + ".log", Log.LogLevel.Debug);
				logger.Debug ("Started reader on port " + port);
			}
			~Reader ()
			{
				Dispose (false);
			}
			protected void Dispose (bool flag)
			{
				if (flag) {
					myserver.Dispose();
					id=null;
					buffer.Clear();
					buffer=null;
				}
			}
			public void Dispose ()
			{
				Dispose (true);
			}
			private bool HandleIncommingData (string data)
			{
				try {
					string tagid = "Get id from data";
					DateTime tagread = DateTime.Now;
					buffer.Add (new BufferData (new Tag (tagid), tagread));
					bufferchange (buffer.Count, id);
					return true;
				} catch (Exception ex) {
					logger.Error ("RFID - Reader - HandleIncommingData - " + ex.Message);
					return false;
				}
			}
			private string HandleIncommingRequest (string data)
			{
				try {
					List<BufferData> mydata = null;
					lock (buffer) {
						mydata = new List<BufferData> (buffer);
						buffer.Clear ();
					}
					bufferchange (buffer.Count, id);
					return Communication.Content.EncodeObject<List<BufferData>> (mydata);
				} catch (Exception ex) {
					logger.Error ("RFID - Reader - HandleIncommingRequest - " + ex.Message);
					return null;
				}
			}
			public static string Encode (string data, TransactionType type)
			{
				return type.ToString () + ":" + data;
			}
		}
	}
}
