using System;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading.Tasks;

namespace Elwig.Helpers.Weighing {
    public class GassnerScale : IScale {

        protected SerialPort Serial = null;
        protected StreamReader Reader;
        protected StreamWriter Writer;

        public string Manufacturer => "Gassner";
        public int InternalScaleNr => 1;
        public string Model { get; private set; }
        public string ScaleId { get; private set; }
        public bool IsReady { get; private set; }
        public bool HasFillingClearance { get; private set; }
        public int? WeightLimit { get; private set; }
        public string? LogPath { get; private set; }

        public GassnerScale(string id, string model, string connection) {
            ScaleId = id;
            Model = model;
            IsReady = true;
            HasFillingClearance = false;

            if (!connection.StartsWith("serial:"))
                throw new ArgumentException("Unsupported scheme");

            Serial = Utils.OpenSerialConnection(connection);
            Writer = new(Serial.BaseStream, Encoding.ASCII, -1, true);
            Reader = new(Serial.BaseStream, Encoding.ASCII, false, -1, true);
        }

        public void Dispose() {
            Writer.Close();
            Reader.Close();
            Serial.Close();
            GC.SuppressFinalize(this);
        }

        public async Task<WeighingResult> Weigh(bool incIdentNr) {
            await Writer.WriteAsync(incIdentNr ? "\x05" : "?");
            // TODO receive response
            return new();
        }

        public async Task<WeighingResult> GetCurrentWeight() {
            return await Weigh(false);
        }

        public async Task<WeighingResult> Weigh() {
            return await Weigh(true);
        }

        public async Task Empty() { }

        public async Task GrantFillingClearance() { }

        public async Task RevokeFillingClearance() { }
    }
}