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

namespace ChaKi.Service.DependencyEdit
{
    internal class OperationChangeTag : Operation
    {
        private Link m_Link;
        private string m_OldTag;
        private string m_NewTag;

        public OperationChangeTag(Link link, string oldTag, string newTag)
        {
            m_Link = link;
            m_OldTag = oldTag;
            m_NewTag = newTag;
        }

        public override void Execute(DepEditContext ctx)
        {
            if (m_Link == null || m_NewTag == null)
            {
                throw new NullReferenceException();
            }
            Tag newTag = FindLinkTag(m_NewTag, ctx);
            if (newTag == null)
            {
                throw new Exception(string.Format("Cannot Find Link Tag: {0}", m_NewTag));
            }
            m_Link.Tag = newTag;
            ctx.Flush();
        }

        public override void UnExecute(DepEditContext ctx)
        {
            if (m_Link == null || m_OldTag == null)
            {
                throw new NullReferenceException();
            }
            Tag oldTag = FindLinkTag(m_OldTag, ctx);
            if (oldTag == null)
            {
                throw new Exception(string.Format("Cannot Find Link Tag: {0}", m_OldTag));
            }
            m_Link.Tag = oldTag;
            ctx.Flush();
        }

        public override string ToIronRubyStatement(DepEditContext ctx)
        {
            return string.Format("#svc.ChangeLinkTag({0},\"{1}\",\"{2}\") : not supported", m_Link.ID, m_OldTag, m_NewTag);
        }

        public override string ToString()
        {
            return string.Format("{{OperationChangeTag:link={0}, oldTag={1}, newTag={2}}}", m_Link, m_OldTag, m_NewTag);
        }
    }
}
