using System;
using ChaKi.Entity.Corpora.Annotations;
using ChaKi.Entity.Corpora;
using NHibernate;

namespace ChaKi.Service.DependencyEdit
{
    internal class OperationCreateSegment : Operation
    {
        private CharRange m_Range;
        private Segment m_Segment;
        private string m_TagName;

        public OperationCreateSegment(CharRange range, string tagName)
        {
            m_Range = range;
            m_TagName = tagName;
        }

        public override void Execute(DepEditContext ctx)
        {
            Segment seg = new Segment();
            seg.Sentence = ctx.Sen;
            seg.Doc = ctx.Sen.ParentDoc;
            seg.Tag = ctx.Proj.FindTag(Tag.SEGMENT, m_TagName);
            if (seg.Tag == null)
            {
                Tag t = new Tag(Tag.SEGMENT, m_TagName) { Parent = ctx.Proj.TagSetList[0], Version = ctx.TSVersion };
                ctx.Proj.TagSetList[0].AddTag(t);
                seg.Tag = t;
                ctx.Save(t);
            }
            seg.StartChar = m_Range.Start.Value + ctx.Sen.StartChar;
            seg.EndChar = m_Range.End.Value + ctx.Sen.StartChar;
            seg.Proj = ctx.Proj;
            seg.User = ctx.User;
            seg.Version = seg.Tag.Version;
            ctx.Save(seg);
            m_Segment = seg;
            ctx.Flush();
        }

        public override void UnExecute(DepEditContext ctx)
        {
            ctx.Delete(m_Segment);
            m_Segment = null;
            ctx.Flush();
        }

        public override string ToIronRubyStatement(DepEditContext ctx)
        {
            return string.Format("#svc.CreateSegment(c+({0}), c+({1}), \"{2}\") : not supported",
                m_Range.Start + ctx.Sen.StartChar - ctx.CharOffset,
                m_Range.End + ctx.Sen.StartChar - ctx.CharOffset,
                m_TagName);
        }

        public override string ToString()
        {
            return string.Format("{{CreateSegment:{0}}}", m_Range);
        }
    }
}
