using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Data;
using System.ComponentModel;
using Platform.Common.BasicFunctions;

namespace Platform.Controls.AdornerContainer
{
   [DesignTimeVisible(false)]
   public class TextLengthAdorner:Adorner
   {
       private VisualCollection _visCollec;
       private TextBlock _rec;
       private TextBox _tb;
       protected override int VisualChildrenCount
       {
           get
           {
               return _visCollec.Count;
           }
       }

       public string LengthText
       {
           set { _rec.Text = value; }
       }
       public TextLengthAdorner(UIElement ele)
           : base(ele)
       {
           if (ele is TextBox)
           {
               _tb =(TextBox) ele;
               Binding bd = new Binding("IsVisible");
               bd.Source = _tb;
               bd.Mode = BindingMode.OneWay;
               bd.Converter = new BoolToVisibilityConverter();
               this.SetBinding(TextBox.VisibilityProperty, bd);
               _visCollec = new VisualCollection(this);
               _rec = new TextBlock();
               _rec.SizeChanged += new SizeChangedEventHandler(rec_SizeChanged);
               _rec.FontSize = 12;
               _rec.VerticalAlignment = VerticalAlignment.Top;
               _rec.SetBinding(TextBlock.TextProperty, new Binding("Text") 
               { 
                   Source = _tb,
                   Converter = new TextToEncodingLengthConverter()
               });
               _visCollec.Add(_rec);

           }
       }

       /// <summary>
       /// 重新定位子元素
       /// </summary>
       private void Arrange()
       {
           Rect r = new Rect(this._tb.ActualWidth + 2, 6, this._rec.ActualWidth, this.AdornedElement.DesiredSize.Height);
           _rec.Arrange(r);
       }

       protected override Size ArrangeOverride(Size finalSize)
       {
           this.Arrange();
           return finalSize;
       }

       private void rec_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
       {
           // textblock大小发生变化意味着里面字符长度发生变化，所以需要重新计算装饰器大小
           this.Arrange();
       }
       protected override Visual GetVisualChild(int index)
       {
           return _visCollec[index];
       }
   }
}
