/*
 * Copyright 2014 Daniel Rivera (danielrr@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace LetThereBeLight
{
    class LightMachine : IState
    {
        public LightMachine(ShellApp.Settings settings)
        {
            this.settings = settings;
            this.settings.Button.OnInterrupt += new NativeEventHandler(button_OnInterrupt);
        }

        public void Initialize()
        {
            if (State == null)
            {
                State = new NeedSystemTimeState(this);
            }
        }

        public void ButtonPressed()
        {
            if (State != null)
            {
                State.ButtonPressed();
            }
        }

        public void Dispose()
        {
            this.settings.Button.OnInterrupt -= this.button_OnInterrupt;
            State = null;
        }

        public IState State
        {
            get
            {
                return currentState;
            }
            set
            {
                Debug.Print("Changing state from " + ((currentState == null) ? "null" : currentState.GetType().ToString()) + " to " + ((value == null) ? "null" : value.GetType().ToString()));
        
                if (this.currentState != null)
                {
                    IState oldState = currentState;
                    currentState = null;
                    oldState.Dispose();
                }

                currentState = value;

                if (currentState != null)
                {
                    currentState.Initialize();
                }
            }
        }

        public ShellApp.Settings Settings
        {
            get { return settings; }
        }

        private IState currentState;
        private ShellApp.Settings settings;

        private void button_OnInterrupt(uint pin, uint edge, DateTime time)
        {
            bool up = (edge == 0);

            if (up)
            {
                ButtonPressed();
            }
        }
    }
}