//------------------------------------------------------------------------------
// Copyright (C) 2008 Invensys Systems Inc.  All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//------------------------------------------------------------------------------

using System;
using System.Runtime.InteropServices;
using System.Collections;
using ArchestrA.Core;
using ArchestrA.Toolkit;

namespace ArchestrA.Toolkit.Watchdog
{
    [Guid("0fba961c-3462-49d6-9963-11aac3c6e9d1")]
    /// <summary>
    /// Summary description for WatchdogConfigtime
    /// </summary>
    public class WatchdogConfigtime : ConfigtimeBase
    {
        #region Attributes - Toolkit generated code
        // The following C# properties have been defined to simplify access to
        // attribute values - do not modify the contents of this region with
        // the code editor.
        private bool Timeout_Alarmed
        {
            get { return GetValue("Timeout.Alarmed"); }
            set { SetValue("Timeout.Alarmed", (value)); }
        }

        private CMxBoolean Stats_Enable
        {
            get { return InternalReferenceOnly.Stats_Enable; }
            set { InternalReferenceOnly.Stats_Enable.Set(value); }
        }

        private bool TimeSinceChange_Historized
        {
            get { return GetValue("TimeSinceChange.Historized"); }
            set { SetValue("TimeSinceChange.Historized", (value)); }
        }

        private CMxElapsedTime Timeout_Limit
        {
            get { return InternalReferenceOnly.Timeout_Limit; }
            set { InternalReferenceOnly.Timeout_Limit.Set(value); }
        }



        public __InputPrimitive1 InputPrimitive1 = null;

        public class __InputPrimitive1
        {
            public SupportWrapper Wrapper = new SupportWrapper();

            private CMxReference _InputSource = null;

            public CMxReference InputSource
            {
                get { if (_InputSource == null) { _InputSource = new CMxReference(Wrapper, "MonitoredBit.InputSource"); } return _InputSource; }
                set { if (_InputSource == null) { _InputSource = new CMxReference(Wrapper, "MonitoredBit.InputSource"); } _InputSource.Set(value); }
            }

            private CMxDataType _DataType = null;

            public CMxDataType DataType
            {
                get { if (_DataType == null) { _DataType = new CMxDataType(Wrapper, "MonitoredBit.DataType"); } return _DataType; }
                set { if (_DataType == null) { _DataType = new CMxDataType(Wrapper, "MonitoredBit.DataType"); } _DataType.Set(value); }
            }

            public __InputPrimitive1(AObjectBase baseClass)
            {
                Wrapper.baseClass = baseClass;
            }

        }

        #endregion Attributes

        #region Internal Reference Only
        //Toolkit code required to access the attributes declared in the Object Class
        private WatchDog InternalReferenceOnly = null;
        #endregion Internal Reference Only

        #region Declarations
        //Declare Configtime Class Variables here.
        //Variables declared in this region are available to all methods 
        //in the Configtime Class.


        #endregion Declarations


        public WatchdogConfigtime()
        {
            InternalReferenceOnly = new WatchDog();
            this.AObjectInstance = InternalReferenceOnly;

            #region Configuration Event Registration - Toolkit generated code
            // Required region for Configuration Events - do not modify 
            // the contents of this region with the code editor.
            this.ConfigtimeInitialize += new ConfigtimeInitializeDelegate(WatchdogConfigtime_ConfigtimeInitialize);
            this.ConfigtimeValidate += new ConfigtimeValidateDelegate(WatchdogConfigtime_ConfigtimeValidate);
            this.ConfigtimeMigrate += new MigrateDelegate(WatchdogConfigtime_ConfigtimeMigrate);
            this.ConfigtimeDynamic += new ConfigtimeDynamicSetHandlerDelegate(WatchdogConfigtime_ConfigtimeDynamic);
            this.PreValidate += new ObjectEventDelegate(WatchdogConfigtime_PreValidate);
            this.PostCreate += new ObjectEventDelegate(WatchdogConfigtime_PostCreate);
            #endregion Configuration Event Registration

            #region Optional Configuration Event Registration - Toolkit generated code
            // Required region for Configuration Events - do not modify 
            // the contents of this region with the code editor.
            // Optional events are enabled by the ObjectAttributes.Events 
            // attribute in the Object class.
            #endregion Optional Configuration Event Registration

            #region Configtime Set Handler Registration – Toolkit generated code
            // Required method for Configtime SetHandlers.  
            // Changes made using the code editor will appear in the Toolkit Editor.
            // 
            // WARNING: Changes made to this region will result in a Shape Change.


            //	TODO: Configtime SetHandler registration
            //	this.RegisterConfigtimeSetHandler("Example_001", new ConfigtimeSetHandlerDelegate(Example_001SetHandler));
			this.RegisterConfigtimeSetHandler("Timeout.Alarmed", new ConfigtimeSetHandlerDelegate(Timeout_AlarmedSetHandler));
			this.RegisterConfigtimeSetHandler("TimeSinceChange.Historized", new ConfigtimeSetHandlerDelegate(TimeSinceChange_HistorizedSetHandler));
            this.RegisterConfigtimeSetHandler("Stats.Enable", new ConfigtimeSetHandlerDelegate(Stats_EnableSetHandler));
            this.RegisterConfigtimeSetHandler("Timeout.Limit", new ConfigtimeSetHandlerDelegate(Timeout_LimitSetHandler));
            #endregion Configtime Set Handler Registration

            #region Primitive Wrapper Initialization - Toolkit generated code
            InputPrimitive1 = new __InputPrimitive1(this);
            #endregion Primitive Wrapper Initialization

        }

        private void WatchdogConfigtime_ConfigtimeInitialize(object sender)
        {
            //------------------------------------------------------------------------------
            //	TODO: Configtime Event - Initialize
            //
            //  Any custom initialization can be done here, including caching of attribute  
            //  values, primitive IDs etc.
            //------------------------------------------------------------------------------
        }

        private void WatchdogConfigtime_ConfigtimeMigrate(object sender, ref MigrateHandler migrate)
        {
            //------------------------------------------------------------------------------
            //	TODO: Configtime Event - Migrate
            //
            //  Migrate executes when importing a template into a Galaxy that contains 
            //  a previous version (major) of the template. The template must be derived or
            //  instantiated for migrate to execute.
            //
            //  Migrate provides access to the previous versions attribute information. 
            //  A typical application for migrate code is to preserve attribute values 
            //  when an attribute name has changed (refer to the Example code below).  
            //  
            //  To enable this event the migrate option must be configured via the Toolkit
            //  Editor or in code (i.e. [ObjectAttributes.AMigrate("1","2")]).
            //
            //  If no implementation is provided, the system will copy all attribute values 
            //  from the old object to the new one by matching the attribute names.
            //------------------------------------------------------------------------------

            #region Example code
            //      //Check major version of previous template
            //      if (migrate.MajorVersion() == 1)
            //      {
            //          //Attribute "Eg_001" has been renamed to "Example_001". 
            //          //Transfer attribute value, lock and security classification
            //          Example_001 = migrate.GetValue("Eg_001");               //Gets value
            //          Example_001.Locked = migrate.GetLocked("Eg_001");       //Gets lock status
            //          Example_001.Security = migrate.GetSecurity("Eg_001");   //Gets Security Classification
            //
            //          //Transfer primitive values
            //          SetValue("Example_001.TrendHi", migrate.GetValue("Eg_001.TrendHi"));
            //          SetValue("Example_001.TrendHi", EATTRIBUTEPROPERTY.idxAttribPropLocked, migrate.GetLocked("Eg_001.TrendHi"));   
            //
            //          //Automatically migrate all child primitives
            //          migrate.AutoMigrateChildPrimitives = true;
            //      }

            #endregion
        }

        private void WatchdogConfigtime_ConfigtimeValidate(object sender, ref EPACKAGESTATUS status)
        {
            //------------------------------------------------------------------------------
            //	TODO: Configtime Event - Validate
            //
            //  Validate sets the warning or error text for the object.
            //  It is used to check conditions that would not be checked using
            //	a SetHandler, such as reporting that an object was not
            //  configured, or that combinations of attributes are illegal.
            //      
            //	Other than calling AddWarningMessage or AddErrorMessage, Validate
            //	should never modify the state of the object.
            //------------------------------------------------------------------------------

            #region Example code
            //      if (MyTestDefaultState)
            //      {
            //          //Add a warning message using the dictionay phrase ID "ObjectStillInDefaultState"
            //          AddWarningMessage(GetText("ObjectStillInDefaultState"));
            //          
            //          //Change the status to Warning if the current status is Good
            //          if (status == EPACKAGESTATUS.ePackageGood)
            //          {
            //              status = EPACKAGESTATUS.ePackageWarning;
            //          }
            //      }
            //
            //      if (MyTestAttributeCombinationValid)
            //      {
            //          //Add a warning message using the dictionay phrase ID "AttributeCombinationInvalid"
            //          AddWarningMessage(GetText("AttributeCombinationInvalid"));
            //          
            //          // Change the status to Warning if the current status is Good
            //          if (status == EPACKAGESTATUS.ePackageGood)
            //          {
            //              status = EPACKAGESTATUS.ePackageWarning;
            //          }
            //      }
            #endregion

            //  By default set the object status to Good
            status = EPACKAGESTATUS.ePackageGood;


            //  The following statement will exit validate when validating templates.
            //  Place code that should be validated in templates and instances before this 
            //  statement. Code placed after this statement will execute in instances only.
            if (IsTemplate)
            {
                return;
            }
        }

        private void WatchdogConfigtime_ConfigtimeDynamic(object sender, ref ConfigtimeSetHandlerEventArgs e)
        {

            string attrName = Get(e.attributeHandle.shAttributeId, e.attributeHandle.shPrimitiveId, EATTRIBUTEPROPERTY.idxAttribPropName);

            //------------------------------------------------------------------------------
            //	TODO: Configtime Event - Dynamic Set Handler
            //
            //  Implement set handler code for any dynamic attributes you create with set handlers  
            //------------------------------------------------------------------------------

            #region Example
            // if (attrName == "MyDynamic")
            // {
            //     if (e.Value > 10)
            //     {
            //         LogWarning(string.Format("value for {0} must be less or equal to 10", attrName));
            //     }
            //     else
            //     {
            //         SetValue(attrName, e.Value);
            //     }
            //
            //    
            //     return;
            // }   
            #endregion

            // if unhandled a warning is shown as a reminder
            SetValue(e.attributeHandle.shAttributeId, e.attributeHandle.shPrimitiveId, e.Value);
            LogWarning(string.Format("Uknown set handler for attribute '{0}'", attrName));

        }

        private void WatchdogConfigtime_PostCreate(object sender, object optionalParameter)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostCreate
            //
            //  OnPostCreate is called when an object is first created.
            //
            //  One purpose for implementing this method is to insure that the initial
            //  state of the primitive is valid.
            //
            //  This method can be used by a Resuable Primitive to correct invalid initial 
            //  states that can arise when an attribute value has been overridden. If the 
            //  attribute has a SetHandler with validation or side effects the SetHandler  
            //  does not execute as overrides do not trigger SetHandlers.
            //------------------------------------------------------------------------------

            #region Example code
            //          // If statistics are enabled, add the Statistics virtual primitive
            //          // the way the SetHandler would have done it.
            //          if (StatsEnable) 
            //          {
            //	            AddPrimitive("Statistics", "Statistics1", "Statistics1");
            //          }
            #endregion
        }

        private void WatchdogConfigtime_PreValidate(object sender, object optionalParameter)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreValidate 
            // 
            //  PreValidate is called when the object is about to be validated (e.g. when
            //  an edit session is ending and the object is about to be saved.)
            //
            //  A primitive can modify attributes within this method.
            //
            //  Note: It is often not necessary to perform any actions in OnPreValidate.
            //------------------------------------------------------------------------------
        }

        #region Optional Configuration Events
        //------------------------------------------------------------------------------
        //  TODO: Optional Configtime Events
        //  
        //  Use the Toolkit Editor to enable each optional event or add the event to the 
        //  ObjectAttributes.Events attribute in the object class. 
        //
        //  Multiple events can be enabled using the | delimiter.
        //  
        //  Example:
        //  [ObjectAttributes.Events(a.EventHandlerEnum.OnPreDeploy | a.EventHandlerEnum.OnPreDelete)]
        //
        //------------------------------------------------------------------------------

        private void WatchdogConfigtime_PreUndeploy(object sender, ref SupportEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreUndeploy
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PreUnassign(object sender, ref GeneralEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreUnassign
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PreRename(object sender, ref RenameEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreRename
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PreDeploy(object sender, ref DeployEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreDeploy
            //  
            //  Use the Toolkit Editor to enable this event or add OnPreDeploy to the 
            //  ObjectAttributes.Events attribute in the object class. Multiple events can
            //  be enabled using the | delimiter.
            //
            //      Example: [ObjectAttributes.Events(a.EventHandlerEnum.OnPreDeploy)]
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PreDelete(object sender, ref SupportEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreDelete
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PreCheckIn(object sender, ref SupportEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreCheckIn
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PreAssignTo(object sender, ref GeneralEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PreAssignTo
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostUndeploy(object sender, ref SupportEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostUndeploy
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostUnassignFrom(object sender, ref GeneralEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostUnassignFrom
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostUnassign(object sender, ref GeneralEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostUnassign
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostRename(object sender, ref RenameEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostRename
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostDeploy(object sender, ref SupportEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostDeploy
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostDelete(object sender, ref SupportEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostDelete
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostAssignTo(object sender, ref GeneralEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostAssignTo
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostAssign(object sender, ref GeneralEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostAssign
            //
            //------------------------------------------------------------------------------

        }
        private void WatchdogConfigtime_PostCheckIn(object sender, ref SupportEventArgs e)
        {
            //------------------------------------------------------------------------------
            //  TODO: Configtime Event - PostCheckIn
            //
            //------------------------------------------------------------------------------

        }

        #endregion

        private void TimeSinceChange_HistorizedSetHandler(object sender, ref ConfigtimeSetHandlerEventArgs e)
        {
            // Required Set Handler for Virtual History Primtive.
            // Do not modify this Set Handler via the code editor.
            //
            // WARNING: Changes made to this Set Handler will be overwritten by the code generator.

            if (TimeSinceChange_Historized == e.Value)
            {
                return;
            }

            if (e.Value)
            {
                if (!AddPrimitive("TimeSinceChangeHistory", "TimeSinceChangeHistory1", "TimeSinceChange"))
                {
                    e.Message = PrimitiveResult.message;
                    return; // Add failed
                }
            }
            else
            {
                if (!DeletePrimitive("TimeSinceChangeHistory1"))
                {
                    e.Message = PrimitiveResult.message;
                    return; // Remove Failed failed
                }
            }

            TimeSinceChange_Historized = e.Value;
        }

        private void Timeout_AlarmedSetHandler(object sender, ref ConfigtimeSetHandlerEventArgs e)
        {
            // Required Set Handler for Virtual Alarm Primtive.
            // Do not modify this Set Handler via the code editor.
            //
            // WARNING: Changes made to this Set Handler will be overwritten by the code generator.

            if (Timeout_Alarmed == e.Value)
            {
                return;
            }

            if (e.Value)
            {
                if (!AddPrimitive("TimeoutAlarm", "TimeoutAlarm1", "Timeout"))
                {
                    e.Message = PrimitiveResult.message;
                    return; // Add failed
                }
            }
            else
            {
                if (!DeletePrimitive("TimeoutAlarm1"))
                {
                    e.Message = PrimitiveResult.message;
                    return; // Remove Failed failed
                }
            }

            Timeout_Alarmed = e.Value;
        }

        private void Timeout_LimitSetHandler(object sender, ref ConfigtimeSetHandlerEventArgs e)
        {
            if (e.Value < 0)
            {
                e.Message = GetText("Timeout.Limit must be a positive number.");
            }

            Timeout_Limit.SetHandlerValue = e;
        }

        private void Stats_EnableSetHandler(object sender, ref ConfigtimeSetHandlerEventArgs e)
        {

            if (e.Value == Stats_Enable) return;

            if (e.Value)
            {
                if (!AddPrimitive("Stats", "Stats1", "Stats"))
                {
                    e.Message = PrimitiveResult.message;
                    return; //Add failed
                }
            }
            else
            {
                if (!DeletePrimitive("Stats1"))
                {
                    e.Message = PrimitiveResult.message;
                    return; //delete failed
                }
            }

            Stats_Enable.SetHandlerValue = e;

        }
    }
}

