﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tinkerforge;

namespace AlwaysOff
{
    class MultiRemoteSwitch
    {
        public BrickletRemoteSwitch RemoteSwitch { get; private set; }
        public bool Ready { get; private set; }

        public MultiRemoteSwitch(string uid, IPConnection ipConnection)
        {
            if (string.IsNullOrWhiteSpace(uid))
            {
                throw new ArgumentNullException("uid", "param is Null or Empty");
            }

            if (ipConnection == null)
            {
                throw new ArgumentNullException("ipConnection", "param is Null");
            }

            this.RemoteSwitch = new BrickletRemoteSwitch(uid, ipConnection);
            this.RemoteSwitch.SwitchingDone += RemoteSwitch_SwitchingDone;
            this.Ready = true;
        }

        public string SwitchSocket(byte houseCode, byte receiverCode, byte switchTo)
        {
            string returnMessage = string.Empty;

            if (this.Ready)
            {
                this.Ready = false;

                Task.Factory.StartNew(() =>
                {
                    this.RemoteSwitch.SwitchSocket(houseCode, receiverCode, switchTo);
                });

                returnMessage = string.Format("{0} : {1},{2} -> {3} ", this.RemoteSwitch.UID, houseCode, receiverCode, switchTo);
            }

            return returnMessage;
        }

        protected void RemoteSwitch_SwitchingDone(BrickletRemoteSwitch sender)
        {
            this.Ready = true;
        }
    }
}
