const string _profileIdFieldName = "Profile ID";          //"Profile_X0020_ID";

        public static void CreateClonedMultilingualItem(IAutomaticTranslation automaticTranslationPlugin, SPWeb siteWeb, string listId, string url, string itemId, string lang,
                                                        bool toTranslate, bool discussionBoardEdition)
        {
            try
            {
                using (var currentSite = new SPSite(url))
                    using (SPWeb web = currentSite.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList currentList = web.Lists[new Guid(listId)];

                        //SPItem currentItem;

                        //if (currentList.BaseTemplate == SPListTemplateType.DiscussionBoard)
                        //{
                        //    currentItem = currentList.Folders.
                        //}

                        SPListItem currentItem = currentList.GetItemById(Convert.ToInt32(itemId));

                        string currentItemLanguage = string.Empty;

                        if (currentList.Fields.ContainsField("SharePoint_Item_Language"))
                        {
                            currentItemLanguage = (string)currentItem["SharePoint_Item_Language"];
                            currentItemLanguage = currentItemLanguage.Replace("(SPS_LNG_ALL)", string.Empty).Replace("SPS_LNG_", string.Empty);
                        }

                        var displayedLang = new ArrayList();

                        if (lang == "ALL")
                        {
                            foreach (LanguageItem languageItem in BaseStaticOverride <Dictionaries> .Instance.VisibleLanguages)
                            {
                                if (currentItemLanguage != languageItem.LanguageDestination)
                                {
                                    displayedLang.Add(languageItem.LanguageDestination);
                                }
                            }
                        }
                        else
                        {
                            displayedLang.Add(lang);
                        }

                        foreach (string langTmp in displayedLang)
                        {
                            lang = langTmp;

                            if (currentList.Fields.ContainsField(lang + " version"))
                            {
                                bool       isLinkedItemExist = false;
                                SPListItem cloneItem         = null;
                                if (currentItem[lang + " version"] != null)
                                {
                                    string linkedItemId = currentItem[lang + " version"].ToString();
                                    var    query        = new SPQuery
                                    {
                                        Query = "<Where><Eq><FieldRef Name='ID'/>" +
                                                "<Value Type='Number'>" +
                                                linkedItemId.Remove(linkedItemId.IndexOf(";")) +
                                                "</Value></Eq></Where>",
                                        QueryThrottleMode = SPQueryThrottleOption.Override
                                    };

                                    if ((discussionBoardEdition) && (currentItem.Folder == null))
                                    {
                                        query.ViewAttributes = "Scope='Recursive'";
                                    }

                                    SPListItemCollection collListItems = currentList.GetItems(query);
                                    if (collListItems.Count > 0)
                                    {
                                        foreach (SPListItem listItemTmp in collListItems)
                                        {
                                            string listItemTmpLanguage = listItemTmp["SharePoint_Item_Language"].ToString();
                                            if (listItemTmpLanguage == "SPS_LNG_" + lang)
                                            {
                                                isLinkedItemExist = true;
                                                cloneItem         = listItemTmp;
                                            }
                                        }
                                    }
                                }

                                bool toOverwrite = false;
                                if (currentItem["ItemsAutoCreation"] != null)
                                {
                                    if (currentItem["ItemsAutoCreation"].ToString() == "Overwrite/Create items for all languages")
                                    {
                                        toOverwrite = true;
                                    }
                                }

                                if ((!isLinkedItemExist) || toOverwrite)
                                {
                                    string cloneItemName;

                                    if (currentList.BaseType == SPBaseType.DocumentLibrary)
                                    {
                                        cloneItemName = currentItem.File.Name.Remove(currentItem.File.Name.LastIndexOf(".")) + "_" + lang + currentItem.Name.Substring(currentItem.Name.LastIndexOf("."));
                                    }
                                    else
                                    {
                                        cloneItemName = currentItem.Name + "_" + lang;
                                    }

                                    if (!isLinkedItemExist)
                                    {
                                        if (currentList.BaseType == SPBaseType.DocumentLibrary)
                                        {
                                            byte[] fileBytes = currentItem.File.OpenBinary();
                                            SPFile file      = currentList.RootFolder.Files.Add(currentList.RootFolder.Url + "/" + cloneItemName, fileBytes);
                                            cloneItem                      = file.Item;
                                            cloneItem["Title"]             = cloneItemName;
                                            cloneItem["ItemsAutoCreation"] = "None";
                                            cloneItem.SystemUpdate(false);
                                        }
                                        else
                                        if (currentList.BaseTemplate == SPListTemplateType.DiscussionBoard)
                                        {
                                            string discussionParentId = string.Empty;


                                            //if (currentUrl.IndexOf("&DiscussionParentID=") > -1)
                                            //{
                                            //    discussionParentId = currentUrl.Substring(currentUrl.IndexOf("=", currentUrl.IndexOf("&DiscussionParentID=")) + 1);
                                            //    if (discussionParentId.IndexOf("&") > -1)
                                            //        discussionParentId = discussionParentId.Remove(discussionParentId.IndexOf("&"));
                                            //}

                                            //if (discussionParentId == string.Empty)
                                            //if (web.GetFolder(currentItem.Url).ParentFolder == null)
                                            if (currentItem.Folder != null)
                                            {
                                                cloneItem = SPUtility.CreateNewDiscussion(currentList.Items, cloneItemName); //  currentList.Items.Add();
                                            }
                                            else
                                            {
                                                SPFolder   parentFolder     = web.GetFolder(currentItem.Url).ParentFolder;
                                                SPListItem parentDiscussion = web.GetFolder(currentItem.Url).ParentFolder.Item;

                                                //SPListItem parentDiscussion = currentList.GetItemById(Convert.ToInt32(discussionParentId));

                                                if ((parentDiscussion["SharePoint_Group_Language"] != null) && (Convert.ToInt32(parentDiscussion["SharePoint_Group_Language"]) != 0))
                                                {
                                                    var query = new SPQuery();
                                                    query.Query = "<Where><And><Eq><FieldRef Name=\"SharePoint_Item_Language\" /><Value Type=\"Text\">SPS_LNG_" + lang + "</Value></Eq>" +
                                                                  "<Eq><FieldRef Name='SharePoint_Group_Language'/>" +
                                                                  "<Value Type='Number'>" + parentDiscussion["SharePoint_Group_Language"].ToString() + "</Value></Eq></And></Where>";

                                                    SPListItemCollection clonedDiscussionsCollection = currentList.GetItems(query);

                                                    foreach (SPListItem clonedDiscussion in clonedDiscussionsCollection)
                                                    {
                                                        cloneItem = SPUtility.CreateNewDiscussionReply(clonedDiscussion);
                                                        break;
                                                    }
                                                }
                                            }

                                            cloneItem[SPBuiltInFieldId.Body]        = cloneItemName;
                                            cloneItem[SPBuiltInFieldId.TrimmedBody] = currentItem[SPBuiltInFieldId.TrimmedBody];

                                            cloneItem["Title"]             = cloneItemName;
                                            cloneItem["ItemsAutoCreation"] = "None";

                                            cloneItem.SystemUpdate(false);
                                        }
                                        else
                                        {
                                            cloneItem = currentList.Items.Add();

                                            cloneItem["Title"]             = cloneItemName;
                                            cloneItem["ItemsAutoCreation"] = "None";

                                            cloneItem.SystemUpdate(false);
                                        }
                                    }

                                    var oQuery = new SPQuery
                                    {
                                        QueryThrottleMode = SPQueryThrottleOption.Override
                                    };

                                    if (currentList.BaseType == SPBaseType.DocumentLibrary)
                                    {
                                        oQuery.Query = "<Where><Eq><FieldRef Name='FileLeafRef'/>" +
                                                       "<Value Type='File'>" + cloneItemName + "</Value></Eq></Where>";
                                    }
                                    else
                                    {
                                        oQuery.Query = "<Where><Eq><FieldRef Name='Title'/>" +
                                                       "<Value Type='Text'>" + cloneItemName + "</Value></Eq></Where>";
                                    }

                                    if (currentList.Fields.ContainsField("MetadataToDuplicate"))
                                    {
                                        if (currentItem["MetadataToDuplicate"] != null)
                                        {
                                            string[] metadataToUpdateArray = ((string)currentItem["MetadataToDuplicate"]).Split(';');
                                            foreach (string t in metadataToUpdateArray)
                                            {
                                                if (currentList.Fields.ContainsField(t))
                                                {
                                                    cloneItem[t] = currentItem[t];
                                                    cloneItem.SystemUpdate(false);
                                                }
                                            }
                                        }
                                    }

                                    bool isBodyExist = currentList.Fields.Cast <SPField>().Any(sPFieldTmp => sPFieldTmp.InternalName == "Body");

                                    bool isTitleExist = currentList.Fields.Cast <SPField>().Any(sPFieldTmp => sPFieldTmp.InternalName == "Title");

                                    bool isProfileExist = currentList.Fields.Cast <SPField>().Any(sPFieldTmp => sPFieldTmp.ToString() == _profileFieldName);

                                    string profileId = string.Empty;

                                    if (isProfileExist)
                                    {
                                        profileId = GetProfileId(web, currentItem);
                                    }

                                    TranslationUserAccount translationUserAccount = null;

                                    if (automaticTranslationPlugin != null)
                                    {
                                        translationUserAccount = automaticTranslationPlugin.LoadUserAccount(web.Site.RootWeb, currentItemLanguage);
                                    }

                                    if (isBodyExist && (currentItem["Body"] != null))
                                    {
                                        string bodyContentToTranslate = currentItem["Body"].ToString();
                                        string bodyContentTranslated  = bodyContentToTranslate;

                                        if ((currentItem["AutoTranslation"] != null) && (currentItemLanguage != lang))
                                        {
                                            if ((currentItem["AutoTranslation"].ToString() == "Yes") || toTranslate)
                                            {
                                                if (automaticTranslationPlugin != null)
                                                {
                                                    bodyContentTranslated  = automaticTranslationPlugin.TranslateText(bodyContentToTranslate, currentItemLanguage, lang, profileId, translationUserAccount, true);
                                                    bodyContentTranslated += " " + HttpRuntime.Cache["AlphamosaikMessageForAutotranslateText"];
                                                }
                                                else
                                                {
                                                    bodyContentTranslated = bodyContentToTranslate;
                                                }

                                                if ((currentList.BaseTemplate == SPListTemplateType.DiscussionBoard) && (cloneItem[SPBuiltInFieldId.TrimmedBody] != null))
                                                {
                                                    if (automaticTranslationPlugin != null)
                                                    {
                                                        cloneItem[SPBuiltInFieldId.TrimmedBody] = automaticTranslationPlugin.TranslateText(currentItem[SPBuiltInFieldId.TrimmedBody].ToString(), currentItemLanguage,
                                                                                                                                           lang, profileId, translationUserAccount, true);

                                                        if (!string.IsNullOrEmpty(cloneItem[SPBuiltInFieldId.TrimmedBody].ToString()))
                                                        {
                                                            cloneItem[SPBuiltInFieldId.TrimmedBody] += " " + HttpRuntime.Cache["AlphamosaikMessageForAutotranslateText"];
                                                        }
                                                    }
                                                    else
                                                    {
                                                        cloneItem[SPBuiltInFieldId.TrimmedBody] = currentItem[SPBuiltInFieldId.TrimmedBody];
                                                    }
                                                }
                                            }
                                        }

                                        if (currentList.BaseTemplate == SPListTemplateType.DiscussionBoard)
                                        {
                                            CopyDiscussionAttachments(currentItem, cloneItem);
                                        }

                                        cloneItem["Body"] = bodyContentTranslated;
                                        cloneItem.SystemUpdate(false);
                                    }

                                    if (currentList.BaseType != SPBaseType.DocumentLibrary)
                                    {
                                        if (isTitleExist && (currentItem["Title"] != null))
                                        {
                                            string titleContentToTranslate = currentItem["Title"].ToString();
                                            string titleContentTranslated  = titleContentToTranslate;
                                            if (currentItem["AutoTranslation"] != null)
                                            {
                                                if (automaticTranslationPlugin != null && ((currentItem["AutoTranslation"].ToString() == "Yes") || toTranslate))
                                                {
                                                    titleContentTranslated = automaticTranslationPlugin.TranslateText(titleContentTranslated, currentItemLanguage, lang, profileId, translationUserAccount, false);
                                                }
                                            }

                                            cloneItem["Title"] = titleContentTranslated;
                                            cloneItem.SystemUpdate(false);
                                        }
                                    }
                                    else
                                    {
                                        if (currentItem["AutoTranslation"] != null)
                                        {
                                            if ((currentItem["AutoTranslation"].ToString() == "Yes") || toTranslate)
                                            {
                                                if (currentList.BaseTemplate == (SPListTemplateType)(850))
                                                {
                                                    string pageContentToTranslate = string.Empty;

                                                    if (currentItem["PublishingPageContent"] != null)
                                                    {
                                                        pageContentToTranslate = currentItem["PublishingPageContent"].ToString();
                                                    }

                                                    if (currentList.Fields.ContainsField("PublishingPageContent"))
                                                    {
                                                        if (automaticTranslationPlugin != null)
                                                        {
                                                            cloneItem["PublishingPageContent"] = automaticTranslationPlugin.TranslateText(pageContentToTranslate, currentItemLanguage,
                                                                                                                                          lang, profileId, translationUserAccount, true);
                                                        }
                                                        else
                                                        {
                                                            cloneItem["PublishingPageContent"] = pageContentToTranslate;
                                                        }

                                                        cloneItem.SystemUpdate(false);
                                                    }
                                                }
                                                else if (automaticTranslationPlugin != null && automaticTranslationPlugin.SupportFileTranslation())
                                                {
                                                    cloneItem.SystemUpdate(false);
                                                    lock (cloneItem)
                                                    {
                                                        byte[] fileBytes = currentItem.File.OpenBinary();
                                                        fileBytes = automaticTranslationPlugin.TranslateFile(fileBytes, currentItemLanguage, lang, profileId, translationUserAccount, currentItem.File.Name);
                                                        cloneItem.File.SaveBinary(fileBytes);
                                                    }
                                                }
                                            }
                                        }

                                        if (currentList.BaseTemplate == (SPListTemplateType)(850))
                                        {
                                            CreatePublishingPage(currentItem, cloneItem, web, toOverwrite);
                                        }
                                    }


                                    url = url.Replace("?SPS_Trans_Code=CreateClonedMultilingualItem&", "?").Replace("&SPS_Trans_Code=CreateClonedMultilingualItem", string.Empty);
                                    Utilities.SetItemLanguage(siteWeb, listId, url, cloneItem.ID.ToString(), lang);
                                    Utilities.LinkItemWith(siteWeb, listId, url, itemId, cloneItem.ID.ToString());
                                }
                                else
                                {
                                    if (HttpContext.Current != null)
                                    {
                                        HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("?SPS_Trans_Code=CreateClonedMultilingualItem&", "?")
                                                                              .Replace("&SPS_Trans_Code=CreateClonedMultilingualItem", string.Empty), false);
                                    }
                                }
                            }
                            else
                            {
                                if (HttpContext.Current != null)
                                {
                                    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("?SPS_Trans_Code=CreateClonedMultilingualItem&", "?")
                                                                          .Replace("&SPS_Trans_Code=CreateClonedMultilingualItem", string.Empty), false);
                                }
                            }
                        }
                    }

                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("?SPS_Trans_Code=CreateClonedMultilingualItem&", "?")
                                                          .Replace("&SPS_Trans_Code=CreateClonedMultilingualItem", string.Empty), false);
                }
            }
            catch (Exception exc)
            {
                Utilities.LogException("Error in Translator2010.TranslatorAutoTranslation.CreateClonedMultilingualItem: " + exc.Message, EventLogEntryType.Warning);
            }
        }
        /// <summary>
        /// Add a term to the dictionary
        /// </summary>
        /// <param name="term">Term to add</param>
        /// <param name="defaultLang">Default language</param>
        /// <returns>ItemStatus after the add</returns>
        public ItemStatus AddTerm(string term, string defaultLang)
        {
            try
            {
                SPListItemCollection collListItems = GetTerms(term, defaultLang);

                var resultQueryList = new ArrayList();

                if (collListItems.Count > 0)
                {
                    if (List.Fields.ContainsField(defaultLang))
                    {
                        foreach (SPListItem currentItem in collListItems)
                        {
                            if (term.Trim() == currentItem[defaultLang].ToString().Trim())
                            {
                                resultQueryList.Add(currentItem);
                            }
                        }
                    }
                }

                ItemStatus itemStatus = ItemStatus.None;

                if (resultQueryList.Count > 0)
                {
                    foreach (SPListItem currentItem in resultQueryList)
                    {
                        foreach (LanguageItem languageItem in Dictionaries.Instance.VisibleLanguages)
                        {
                            if (currentItem[languageItem.LanguageDestination] == null ||
                                string.IsNullOrEmpty(currentItem[languageItem.LanguageDestination].ToString()))
                            {
                                if (_automaticTranslationPlugin != null)
                                {
                                    TranslationUserAccount translationUserAccount = _automaticTranslationPlugin.LoadUserAccount(Web, null);
                                    currentItem[languageItem.LanguageDestination] = "SPS_ADDED_" + _automaticTranslationPlugin.TranslateText(term.Trim(), defaultLang, languageItem.LanguageDestination, null, translationUserAccount, false);
                                }
                                else
                                {
                                    currentItem[languageItem.LanguageDestination] = "SPS_ADDED_" + term.Trim();
                                }

                                itemStatus = ItemStatus.Updated;
                            }
                        }

                        if (itemStatus == ItemStatus.Updated)
                        {
                            if (List.Fields.ContainsField("isCustomize"))
                            {
                                currentItem["isCustomize"] = true;
                            }

                            Web.AllowUnsafeUpdates = true;
                            currentItem.SystemUpdate(false);
                            Web.AllowUnsafeUpdates = false;

                            return(itemStatus);
                        }

                        break;
                    }

                    return(ItemStatus.Existing);
                }

                SPListItem newItem = List.Items.Add();

                if (List.Fields.ContainsField("isCustomize"))
                {
                    newItem["isCustomize"] = true;
                }

                if (List.Fields.ContainsField(defaultLang))
                {
                    newItem[defaultLang] = "SPS_ADDED_" + term.Trim();
                }

                foreach (LanguageItem languageItem in Dictionaries.Instance.VisibleLanguages)
                {
                    if (List.Fields.ContainsField(languageItem.LanguageDestination))
                    {
                        if (_automaticTranslationPlugin != null)
                        {
                            TranslationUserAccount translationUserAccount = _automaticTranslationPlugin.LoadUserAccount(Web, null);
                            newItem[languageItem.LanguageDestination] = "SPS_ADDED_" + _automaticTranslationPlugin.TranslateText(term.Trim(), defaultLang, languageItem.LanguageDestination, null, translationUserAccount, false);
                        }
                        else
                        {
                            newItem[languageItem.LanguageDestination] = "SPS_ADDED_" + term.Trim();
                        }

                        itemStatus = ItemStatus.Inserted;
                    }
                }

                Web.AllowUnsafeUpdates = true;
                newItem.SystemUpdate(false);
                Web.AllowUnsafeUpdates = false;

                return(itemStatus);
            }
            catch (Exception e)
            {
                Utilities.LogException("AddToDictionary", e, EventLogEntryType.Warning);
                throw;
            }
        }