// Created with MonoDevelop
//
//    Copyright (C) 2012 Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.



using System;
using System.Collections.Generic;

using Hiperscan.Spectroscopy;
using Hiperscan.Unix;


namespace Hiperscan.SGS
{
	internal class Device0_18 : Device0_17
	{
		protected new class Protocol : Device0_17.Protocol
		{
			public static readonly Parameter WriteAdcBuffer         = new Parameter('I', 'M', typeof(byte[]), 10000);
			public static readonly Parameter ReadTemperatureHistory = new Parameter('T', 'G', typeof(byte[]), 0);
		}
		
		public Device0_18(DeviceInfo info, VersionInfo version_info) : base (info, version_info)
		{
		}

		public override Spectrum AcquireAdcBufferSpectrum(byte[] key, UInt16[] buf)
		{
			this.SetMaintenanceMode(key);
			
			Protocol.Parameter parameter = new Protocol.Parameter(Protocol.WriteAdcBuffer);
			
			List<byte> bbuf = new List<byte>();

			foreach (UInt16 val in buf)
			{
				bbuf.AddRange(BitConverter.GetBytes(val));
			}
			
			if (bbuf.Count != parameter.Count)
				throw new SGSException(Catalog.GetString("Unexpected ADC buffer length."), this);
			
			parameter.ByteArray = bbuf.ToArray();
			
			if (!this.WriteParameter(parameter, 30000))
				throw new SGSException(Catalog.GetString("Operation failed."), this);

			return this.Single();
		}

		protected override void Connect()
		{
			base.Connect();
			this.ReadTemperatureHistory();
			Console.WriteLine(this.TemperatureHistory.ToString());
		}

		internal void ReadTemperatureHistory()
		{
			byte[] buf = this.ReadByteArrayParameter(Protocol.ReadTemperatureHistory);

			if (buf.Length == 1 && buf[0] == 0)
				return;

			if (buf.Length < sizeof(Int16) || buf.Length % sizeof(Int16) != 0)
				throw new SGSException(Catalog.GetString("Invalid device response."), this);

			UInt16 interval = BitConverter.ToUInt16(buf, 0);
			List<double> temperatures = new List<double>();
			for (int ix=sizeof(Int16); ix < buf.Length; ix += sizeof(Int16))
			{
				temperatures.Add((double)BitConverter.ToUInt16(buf, ix) / 100.0);
			}

			this.temperature_history = new TemperatureHistory(interval, temperatures.ToArray());
		}
	}
}
