//------------------------------------------------------------------------------
// 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 ArchestrA.Core;
using ArchestrA.Toolkit;

namespace ArchestrA.Toolkit.Watchdog
{
    [Guid("057251b9-4dfa-4216-80ae-0981f7bc63e9")]
    /// <summary>
    /// Summary description for WatchdogConfigtime
    /// </summary>
    public class StatsConfigtime : 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 TimeoutCnt_Historized
        {
            get { return GetValue("TimeoutCnt.Historized"); }
            set { SetValue("TimeoutCnt.Historized", (value)); }
        }



        #endregion Attributes

        #region Internal Reference Only
        //Toolkit code required to access the attributes declared in the Object Class
        private Stats 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 StatsConfigtime()
        {
            InternalReferenceOnly = new Stats();
            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(StatsConfigtime_ConfigtimeInitialize);
            this.ConfigtimeValidate += new ConfigtimeValidateDelegate(StatsConfigtime_ConfigtimeValidate);
            this.ConfigtimeMigrate += new MigrateDelegate(StatsConfigtime_ConfigtimeMigrate);
            this.ConfigtimeDynamic += new ConfigtimeDynamicSetHandlerDelegate(StatsConfigtime_ConfigtimeDynamic);
            this.PreValidate += new ObjectEventDelegate(StatsConfigtime_PreValidate);
            this.PostCreate += new ObjectEventDelegate(StatsConfigtime_PostCreate);
            #endregion 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("TimeoutCnt.Historized", new ConfigtimeSetHandlerDelegate(TimeoutCnt_HistorizedSetHandler));
            #endregion Configtime Set Handler Registration

            #region Primitive Wrapper Initialization - Toolkit generated code
            #endregion Primitive Wrapper Initialization

        }

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

        private void StatsConfigtime_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 StatsConfigtime_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 StatsConfigtime_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 StatsConfigtime_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 StatsConfigtime_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.
            //------------------------------------------------------------------------------
        }

        private void TimeoutCnt_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 (TimeoutCnt_Historized == e.Value)
            {
                return;
            }

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

            TimeoutCnt_Historized = e.Value;
        }

        //TODO: Configtime SetHandler declaration
        //private void Example_001SetHandler(object sender, ref ConfigtimeSetHandlerEventArgs e)
        //{
        //    Example_001 = e.Value;
        //}

    }
}

