namespace PseudoAttributes
{
    using System;
    using Aveva.Pdms.Database;

    /// <summary>
    /// cstandard of category of catreference of hstube of members
    /// </summary>
    class CCStandard
    {
        private static DbAttribute attr;

        public static void Run()
        {
            CCStandard.attr = DbAttribute.GetDbAttribute(":C-CStandard");

            if (CCStandard.attr == null)
                return;

            DbPseudoAttribute.GetStringDelegate attDelegate = new DbPseudoAttribute.GetStringDelegate(CCStandard.AttributeValueCalculation);

            // Для каких типов элементов считать атрибут
            DbPseudoAttribute.AddGetStringAttribute(CCStandard.attr, DbElementTypeInstance.PIPE, attDelegate);
        }

        /// <summary>
        /// Вычисление значения атрибута
        /// </summary>
        /// <param name="ele">Элемент</param>
        /// <param name="att">Атрибут</param>
        /// <param name="qual">Спецификатор</param>
        static private string AttributeValueCalculation(DbElement ele, DbAttribute att, DbQualifier qual)
        {
            if (CCStandard.attr == null || ele.Members().Length == 0)
                return string.Empty;

            // ... members
            DbElement bran = ele.FirstMember();

            // ... hstube of members
            DbElement hstu = bran.GetElement(DbAttributeInstance.HSTU);

            if (hstu.IsNull)
                return "no hsTube of member";

            // ... catreference of hstube of members
            DbElement catRef = hstu.GetElement(DbAttributeInstance.CATR);

            if (catRef.IsNull)
                return "no catReference of hsTube of member";

            // ... category of catreference of hstube of members
            DbElement cate = catRef.Owner;

            // cstandard of category of catreference of hstube of members
            return cate.GetString(DbAttributeInstance.CSTA);
        }
    }
}
