using System;
using System.Collections.Generic;
using System.Linq;
using DummyTMInterface;
using MemoQ.Addins.Common.DataStructures;
using MemoQ.TMInterfaces;

namespace DummyTMPlugin
{
    /// <summary>
    /// Session that perform actual translation.
    /// </summary>
    public class DummyTMSession : SessionBase
    {
        /// <summary>
        /// The source language.
        /// </summary>
        private string srcLangCode;

        /// <summary>
        /// The target language.
        /// </summary>
        private string trgLangCode;

        public DummyTMSession(string srcLangCode, string trgLangCode)
        {
            this.srcLangCode = srcLangCode;
            this.trgLangCode = trgLangCode;
        }

        /// <summary>
        /// Gets the possible translations for a segment from the translation memory.
        /// </summary>
        /// <param name="segment">The segment to be translated.</param>
        /// <param name="precedingSegment">The preceding segment.</param>
        /// <param name="followingSegment">The following segment.</param>
        /// <param name="matchThreshold">The minimum match rate.</param>
        /// <returns>The possible translations of the input segment.</returns>
        public override TMPluginHit[] Lookup(Segment segment, Segment precedingSegment, Segment followingSegment, int matchThreshold)
        {
            List<TMPluginHit> results = new List<TMPluginHit>();
            TMServiceLookupHit[] serviceHits = null;

            try
            {
                serviceHits = DummyTMServiceHelper.Lookup(DummyTMServiceHelper.GetTokenCode(), segment.PlainText, this.srcLangCode, this.trgLangCode);
            }
            catch (Exception ex)
            {
                string englishMessage = string.Format("Lookup error: {0}", ex.Message);
                string localizedMessage = string.Format(LocalizationHelper.Instance.GetResourceString("LookupError"), ex.Message);
                throw new TMPluginException(localizedMessage, englishMessage);
            }

            if (serviceHits != null)
            {
                foreach (var hit in serviceHits)
                {
                    if (hit.MatchRate < matchThreshold)
                        continue;

                    SegmentBuilder srcSegBuilder = new SegmentBuilder();
                    srcSegBuilder.AppendString(hit.SourceString);

                    SegmentBuilder trgSegBuilder = new SegmentBuilder();
                    trgSegBuilder.AppendString(hit.TargetString);

                    // converting the hit returned by the service to a TMPluginHit
                    TMPluginEntry tmpe = new TMPluginEntry(
                        srcSegBuilder.ToSegment(), trgSegBuilder.ToSegment(), hit.LastModified, hit.UserName, hit.CreationDate,
                        hit.CreatingUser, hit.Subject, hit.Domain, "DummyClientID", "DummyProjectID", hit.Document, null, null);
                    results.Add(new TMPluginHit(tmpe, hit.MatchRate, 0) { PluginID = "DummyTM", PluginName = "Dummy TM Plugin" });
                }
            }

            return results.ToArray();
        }

        /// <summary>
        /// Gets the possible concordance lookup results of specific texts.
        /// </summary>
        /// <param name="texts">The texts sent for concordance.</param>
        /// <param name="settings">The settings of the concordance operation.</param>
        /// <returns>The concordance results of the texts.</returns>
        public override TMPluginConcordanceResult Concordance(string[] texts, TMPluginConcordanceSettings settings)
        {
            TMServiceConcordanceItem[] results = null;
            int totalResultCount;
            List<TMPluginConcordanceResult.TMPluginConcordanceItem> concordanceItems = new List<TMPluginConcordanceResult.TMPluginConcordanceItem>();

            try
            {
                results = DummyTMServiceHelper.Concordance(
                    DummyTMServiceHelper.GetTokenCode(),
                    texts,
                    srcLangCode,
                    trgLangCode,
                    settings.CaseSensitive,
                    settings.NumericEquivalence,
                    settings.Limit,
                    out totalResultCount);
            }
            catch (Exception ex)
            {
                string englishMessage = string.Format("Concordance error: {0}", ex.Message);
                string localizedMessage = string.Format(LocalizationHelper.Instance.GetResourceString("ConcordanceError"), ex.Message);
                throw new TMPluginException(localizedMessage, englishMessage);
            }

            if (results != null)
            {
                foreach (var item in results)
                {
                    SegmentBuilder srcSegBuilder = new SegmentBuilder();
                    srcSegBuilder.AppendString(item.SourceString);

                    SegmentBuilder trgSegBuilder = new SegmentBuilder();
                    trgSegBuilder.AppendString(item.TargetString);

                    concordanceItems.Add(new TMPluginConcordanceResult.TMPluginConcordanceItem(
                        item.RangeInfos.ToList().ConvertAll(ri => new TMPluginConcordanceResult.TMPluginConcordanceRangeInfo(ri.Start, ri.Length)).ToArray(),
                        new TMPluginEntry(
                            srcSegBuilder.ToSegment(),
                            trgSegBuilder.ToSegment(),
                            item.LastModified, item.UserName, item.CreationDate, item.CreatingUser, item.Subject,
                            item.Domain, "DummyClientID", "DummyProjectID", item.Document, null, null)));
                }
            }

            return new TMPluginConcordanceResult(
                totalResultCount,
                concordanceItems.ToArray());
        }

        public override void Dispose()
        {
            // dispose your resources if needed
        }
    }
}
