﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Devices.Gpio;

namespace SensorbergIoT_ForeGround
{
    class PayloadHandler
    {
        private const int RED_PIN = 12;
        private const int GREEN_PIN = 13;
        private GpioPin pinRed;
        private GpioPin pinGreen;

        public PayloadHandler()
        {
        }
        public bool Initialize()
        { 
            var gpio = GpioController.GetDefault();

            // Show an error if there is no GPIO controller
            if (gpio == null)
            {
                pinRed = null;
                Debug.WriteLine("There is no GPIO controller on this device.");
                return false;
            }
            pinRed = gpio.OpenPin(RED_PIN);
            pinRed.Write(GpioPinValue.Low);
            pinRed.SetDriveMode(GpioPinDriveMode.Output);

            pinGreen = gpio.OpenPin(GREEN_PIN);
            pinGreen.Write(GpioPinValue.Low);
            pinGreen.SetDriveMode(GpioPinDriveMode.Output);

            Debug.WriteLine("Pin init : succeess");
            return true;
        }

        public void Deinitialize()
        {
            /*
            https://msdn.microsoft.com/en-us/library/windows.devices.gpio.gpiopin.close.aspx
            You cannot call Close methods through Visual C++ component extensions (C++/CX) on Windows Runtime class 
            instances where the class implemented IClosable. 
            Instead, C++/CX code for runtime classes should call the destructor or set the last reference to null.
            */
            pinRed = null;
            pinGreen = null;
        }

        public void HandlePayload(JsonObject payload)
        {
            if(payload == null || pinGreen == null || pinRed == null)
            {
                if (payload != null)
                {
                    Debug.WriteLine("PayloadHandler not initialized");
                }
                return;
            }

            GpioPinValue setToValue = (payload.GetNamedString("status") == "on") ? GpioPinValue.Low : GpioPinValue.High;

            if (payload.GetNamedString("color") == "green")
            {
                pinGreen.Write(setToValue);
            }
            else if (payload.GetNamedString("color") == "red")
            { 
                pinRed.Write(setToValue);
            }
            else
            {
                Debug.WriteLine("unknown color: " + payload.GetNamedString("color"));
            }
        }
    }
}
