public IActionResult Registration(string lastName, string firstName, string patronymic)
 {
     if (string.IsNullOrWhiteSpace(lastName) || string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(patronymic))
     {
         _logger.LogError($"Поля при регистрации оказались пустыми пустые.");
         return(View());
     }
     else
     {
         try
         {
             userFolder = FolderWork.CreateFolderForUser(firstName, lastName, patronymic, _appEnvironment.WebRootPath + @"\Files") + @"\";
         }
         catch (Exception e)
         {
             WriteExceptionInLog(e);
             return(View());
         }
         if (!string.IsNullOrWhiteSpace(userFolder))
         {
             _logger.LogInformation($"Папка для пользователя {firstName} {lastName} {patronymic} была успешно создана.");
             return(RedirectToAction("Login"));
         }
         else
         {
             _logger.LogError($"Папка для пользователя {firstName} {lastName} {patronymic} не была создана.");
             return(View());
         }
     }
 }
        public async Task <IActionResult> UpdateBookmarkAsync(string bookmark, string text, IFormFile image)
        {
            string path = null;

            if (image != null)
            {
                if (Path.GetExtension(image.FileName).Equals(".png") || Path.GetExtension(image.FileName).Equals(".jpg"))
                {
                    path = _appEnvironment.WebRootPath + "/Images/" + image.FileName;
                    try
                    {
                        await FolderWork.SaveImage(image, path);

                        _logger.LogInformation($"Изображение {image.FileName} сохранено по пути {path}.");
                    }
                    catch (Exception e)
                    {
                        _logger.LogError($"Не удалось сохранить изображение {image.FileName}.");
                        WriteExceptionInLog(e);
                        ViewBag.Messages = e.Message.ToString();
                        ViewBag.LongText = wordDocument.GetTextFromDocument();
                        return(View());
                    }
                }
                else
                {
                    ViewBag.Messages = "Неверный формат файла. Должен быть PNG или JPG";
                    ViewBag.LongText = wordDocument.GetTextFromDocument();
                    return(View());
                }
            }

            try
            {
                if (string.IsNullOrWhiteSpace(path))
                {
                    _logger.LogInformation($"Начато изменение закладки {bookmark} на {text}");
                    wordDocument.EditTextInBookmark(bookmark, text);
                    _logger.LogInformation($"Завершилось изменение закладки {bookmark} на {text}");
                }
                else
                {
                    _logger.LogInformation($"Начато изменение изображения закладки {bookmark}");
                    wordDocument.EditImageInBookmark(bookmark, path);
                    _logger.LogInformation($"Завершилось изменение изображения закладки {bookmark}");
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"Message {e.Message}");
                WriteExceptionInLog(e);
                ViewBag.Messages = e.Message.ToString();
                return(Redirect("EditLinks"));
            }
            return(Redirect("EditLinks"));
        }
 public FileResult Download(FileFormat fileFormat)
 {
     try
     {
         FolderWork.SetParametresForDownloadFile(fileFormat, userFolder: HomeController.userFolder, filepath: HomeController.filepath, out byte[] fileBytes, out string fileExtension, out string filename);
         _logger.LogInformation($"Начато скачивание файла {filename}");
         return(File(fileBytes, "application/" + fileExtension, filename));
     }
     catch (Exception e)
     {
         _logger.LogError($"Message {e.Message}");
         WriteExceptionInLog(e);
         ViewBag.Messages = e.Message.ToString();
         return(null);
     }
 }
        private static string GetFilepathAfterConvertSpirePdf(string filepath, Spire.Pdf.FileFormat fileFormat)
        {
            PdfDocument pdfDocument = new PdfDocument();

            pdfDocument.LoadFromFile(filepath);
            if (fileFormat == Spire.Pdf.FileFormat.HTML)
            {
                filepath = FolderWork.CreateForlderForHTML(filepath);
                filepath = $"{filepath}\\html\\{formatWord}.{fileFormat.ToString().ToLower()}";
            }
            else
            {
                filepath = $"{filepath}_{formatWord}.{fileFormat.ToString().ToLower()}";
            }
            pdfDocument.SaveToFile(filepath, fileFormat);
            return(filepath);
        }
        //Подумать над названием
        private static string GetFilepathAfterConvertSpireDoc(string filepath, Spire.Doc.FileFormat fileFormat)
        {
            Document document = new Document();

            document.LoadFromFile(filepath);

            if (fileFormat == Spire.Doc.FileFormat.Html)
            {
                filepath = FolderWork.CreateForlderForHTML(filepath);
                filepath = $"{filepath}\\{formatWord}.{fileFormat.ToString().ToLower()}";
            }
            else
            {
                filepath = $"{filepath}_{formatWord}.{fileFormat.ToString().ToLower()}";
            }
            document.SaveToFile(filepath, fileFormat);
            return(filepath);
        }
        public IActionResult Index(IFormFile file)
        {
            if (file != null)
            {
                var extension = Path.GetExtension(file.FileName);

                if (formats.Contains(extension))
                {
                    filepath = userFolder + file.FileName;

                    //await SaveFile(file, file.FileName, filepath);
                    FolderWork.SaveFile(file, file.FileName, ref filepath, ref userFolder);
                    _logger.LogInformation($"Сохранён файл {filepath}");

                    try
                    {
                        filepath = Conversion.ConvertToWordDocx(filepath);
                    }
                    catch (Exception e)
                    {
                        WriteExceptionInLog(e);
                        return(View());
                    }
                    _logger.LogInformation($"Сохранён переконвентированный файл {filepath}");

                    if (string.IsNullOrWhiteSpace(filepath))
                    {
                        _logger.LogInformation($"Преобразование файла {filepath} невозможно");
                        ViewBag.FileFormatErrorMessage = "Неверный формат файла. Дальнейшее преобразование невозможно!";
                        return(View());
                    }

                    return(RedirectToAction("Index", "Document"));
                }
                else
                {
                    _logger.LogInformation($"Введён не тот формат файла - {extension}. Файл - {file.FileName}.");
                    ViewBag.FileFormatErrorMessage = "Неверный формат файла. Должен быть TXT, RTF, HTML, ODT, DOC, DOCX, PDF";
                    return(View());
                }
            }
            return(View());
        }
        public async Task <IActionResult> Index(string word, string text, string linkType, IFormFile image, string oneOrAll, int count = default)
        {
            try
            {
                string path = null;
                if (image != null)
                {
                    if (Path.GetExtension(image.FileName).Equals(".png") || Path.GetExtension(image.FileName).Equals(".jpg"))
                    {
                        path = _appEnvironment.WebRootPath + "/Images/" + image.FileName;
                        try
                        {
                            await FolderWork.SaveImage(image, path);

                            _logger.LogInformation($"Изображение {image.FileName} сохранено по пути {path}.");
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"Не удалось сохранить изображение {image.FileName}.");
                            WriteExceptionInLog(e);
                            ViewBag.Messages = e.Message.ToString();
                            ViewBag.LongText = wordDocument.GetTextFromDocument();
                            return(View());
                        }
                    }
                    else
                    {
                        ViewBag.Messages = "Неверный формат файла. Должен быть PNG или JPG";
                        ViewBag.LongText = wordDocument.GetTextFromDocument();
                        return(View());
                    }
                }

                if (!string.IsNullOrWhiteSpace(text) & !string.IsNullOrWhiteSpace(word) & !string.IsNullOrWhiteSpace(linkType))
                {
                    if (linkType.Equals("bookmark"))
                    {
                        try
                        {
                            _logger.LogInformation($"Начато создание закладки для текста с параметрами {text}, {word}");
                            if (oneOrAll.Equals("all"))
                            {
                                wordDocument.CreateBookmarksForText(word, text, count);
                            }
                            else if (oneOrAll.Equals("one"))
                            {
                                wordDocument.CreateBookmarkForOneWord(word, text);
                            }
                            _logger.LogInformation($"Завершилось создание закладки для текста с параметрами {text}, {word}");
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"Message {e.Message}");
                            WriteExceptionInLog(e);
                            ViewBag.Messages = e.Message.ToString();
                            ViewBag.LongText = wordDocument.GetTextFromDocument();
                            return(View());
                        }
                    }
                    else if (linkType.Equals("hyperlink"))
                    {
                        try
                        {
                            _logger.LogInformation($"Начато создание гиперссылки для текста с параметрами {text}, {word}");
                            if (oneOrAll.Equals("all"))
                            {
                                wordDocument.CreateHyperlinksForText(word, text, count);
                            }
                            else if (oneOrAll.Equals("one"))
                            {
                                wordDocument.CreateHyperlinkForOneWord(word, text);
                            }
                            _logger.LogInformation($"Завершилось создание гиперссылки для текста с параметрами {text}, {word}");
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"Message {e.Message}");
                            WriteExceptionInLog(e);
                            ViewBag.Messages = e.Message.ToString();
                            ViewBag.LongText = wordDocument.GetTextFromDocument();
                            return(View());
                        }
                    }
                }
                else if (!string.IsNullOrWhiteSpace(path) & !string.IsNullOrWhiteSpace(text) & !string.IsNullOrWhiteSpace(linkType))
                {
                    if (linkType.Equals("hyperlink"))
                    {
                        try
                        {
                            _logger.LogInformation($"Начато создание гиперссылки для изображения с параметрами {text}, {path}");
                            wordDocument.CreatHyperlinkForImage(path, text);
                            _logger.LogInformation($"Завершилось создание гиперссылки для изображения с параметрами {text}, {path}");
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"Message {e.Message}");
                            WriteExceptionInLog(e);
                            ViewBag.Messages = e.Message.ToString();
                            ViewBag.LongText = wordDocument.GetTextFromDocument();
                            return(View());
                        }
                    }
                }
                else if (!string.IsNullOrWhiteSpace(path) & !string.IsNullOrWhiteSpace(word) & !string.IsNullOrWhiteSpace(linkType))
                {
                    if (linkType.Equals("bookmark"))
                    {
                        try
                        {
                            _logger.LogInformation($"Начато создание закладки для изображения с параметрами {text}, {path}");
                            if (oneOrAll.Equals("all"))
                            {
                                wordDocument.CreateBookmarksForImage(path, word, count);
                            }
                            else if (oneOrAll.Equals("one"))
                            {
                                wordDocument.CreateBookmarkByImgeForOneWord(path, word);
                            }
                            _logger.LogInformation($"Завершилось создание закладки для изображения с параметрами {text}, {path}");
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"Message {e.Message}");
                            WriteExceptionInLog(e);
                            ViewBag.Messages = e.Message.ToString();
                            ViewBag.LongText = wordDocument.GetTextFromDocument();
                            return(View());
                        }
                    }
                }



                ViewBag.Messages = wordDocument.Messages;
                ViewBag.LongText = wordDocument.GetTextFromDocument();
                return(View());
            }
            catch (Exception e)
            {
                _logger.LogError($"Message {e.Message}");
                WriteExceptionInLog(e);
                ViewBag.Messages = e.Message.ToString();
                ViewBag.LongText = wordDocument.GetTextFromDocument();
                return(View());
            }
        }
        //private async Task SaveFile(IFormFile file, string filename, string path)
        //{
        //    if (System.IO.File.Exists(path))
        //    {
        //        filename = "NEW_" + filename;
        //        filepath = userFolder + filename;
        //        await SaveFile(file, filename, filepath);
        //    }
        //    else
        //    {
        //        using var fileStream = new FileStream(path, FileMode.CreateNew);
        //        await file.CopyToAsync(fileStream);
        //    }
        //}

        public IActionResult LogIn(string lastName, string firstName, string patronymic)
        {
            if (string.IsNullOrWhiteSpace(lastName) || string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(patronymic))
            {
                return(View());
            }
            else
            {
                string initials = null;
                try
                {
                    initials = FolderWork.GetFolderName(firstName, lastName, patronymic);
                }
                catch (Exception e)
                {
                    WriteExceptionInLog(e);
                    return(View());
                }

                if (string.IsNullOrWhiteSpace(initials))
                {
                    _logger.LogError($"Инициалы пользователя пусты.");
                }

                string absolutPath = _appEnvironment.WebRootPath + @"\Files";

                if (!Directory.Exists(absolutPath))
                {
                    _logger.LogError($"Абсолютный путь {absolutPath} не найден.");
                    Directory.CreateDirectory(absolutPath);
                    _logger.LogInformation($"Создан абсолютный путь {absolutPath}.");
                    return(View());
                }
                try
                {
                    foreach (var item in Directory.GetDirectories(absolutPath))
                    {
                        if (item.Contains(initials))
                        {
                            userFolder = item + @"\";
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError($"Абсолютный путь {absolutPath} не найден.");
                    WriteExceptionInLog(e);
                    Directory.CreateDirectory(absolutPath);
                    _logger.LogInformation($"Создан абсолютный путь {absolutPath}.");
                    return(View());
                }


                if (!string.IsNullOrWhiteSpace(userFolder))
                {
                    _logger.LogInformation($"Пользователь {firstName} {lastName} {patronymic} вошёл в систему.");
                    return(RedirectToAction("Index"));
                }
                else
                {
                    _logger.LogError($"Пользователь {firstName} {lastName} {patronymic} не был найден.");
                    return(View());
                }
            }
        }