<commit_before>﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using ICSharpCode.AvalonEdit;
using MarkdownEdit.ImageUpload;

namespace MarkdownEdit.Controls
{
    public partial class ImageDropDialog
    {
        public TextEditor TextEditor { get; set; }
        public DragEventArgs DragEventArgs { get; set; }
        private bool _canceled;

        public ImageDropDialog()
        {
            InitializeComponent();
            Activated += OnActivated;
        }

        private void OnActivated(object sender, EventArgs eventArgs)
        {
            var position = DragEventArgs.GetPosition(TextEditor);
            var screen = new Point(position.X, position.Y);
            Left = screen.X;
            Top = screen.Y;
        }

        private void OnInsertPath(object sender, RoutedEventArgs e)
        {
            var files = DragEventArgs.Data.GetData(DataFormats.FileDrop) as string[];
            if (files == null) return;
            var file = Path.GetFileNameWithoutExtension(files[0]);
            var path = Uri.EscapeUriString(files[0].Replace('\\', '/'));
            if (path.Contains(":")) path = "file:" + path;
            InsertImageLink(path, file);
            Close();
        }

        private void OnUploadToImgur(object sender, RoutedEventArgs e)
        {
            var files = DragEventArgs.Data.GetData(DataFormats.FileDrop) as string[];
            if (files == null) return;
            var path = files[0];
            var name = Path.GetFileNameWithoutExtension(path);

            UploadProgressChangedEventHandler progress = (o, args) => TextEditor.Dispatcher.InvokeAsync(() =>
            {
                if (_canceled)
                {
                    var webClient = (WebClient)o;
                    webClient.CancelAsync();
                    return;
                }
                var progressPercentage = (int)((args.BytesSent / (double)args.TotalBytesToSend) * 100);
                ImgurMenuItem.Header = (progressPercentage == 100) ? "Processing" : $"{progressPercentage}%";
            });

            Action<string, string> processResult = (link, description) =>
            {
                if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
                {
                    InsertImageLink(link, description);
                }
                else
                {
                    MessageBox.Show(link, App.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            };

            new ImageUploadImgur()
                .UploadBytesAsync(File.ReadAllBytes(path), progress)
                .ContinueWith(task => TextEditor.Dispatcher.InvokeAsync(() => processResult(task.Result, name)))
                .ContinueWith(task => Dispatcher.InvokeAsync(Close));
        }

        private void OnCancel(object sender, RoutedEventArgs e)
        {
            _canceled = true;
            Close();
        }

        private void InsertImageLink(string link, string description)
        {
            TextEditor.Document.Insert(GetInsertOffset(), $"![{description}]({link})\n");
        }

        private int GetInsertOffset()
        {
            var position = DragEventArgs.GetPosition(TextEditor);
            var offset = GetOffsetFromMousePosition(TextEditor, position);
            if (offset == -1) offset = TextEditor.Document.TextLength;
            return offset;
        }

        private static int GetOffsetFromMousePosition(TextEditor textEditor, Point positionRelativeToTextView)
        {
            var textView = textEditor.TextArea.TextView;
            var pos = positionRelativeToTextView;
            if (pos.Y < 0) pos.Y = 0;
            if (pos.Y > textView.ActualHeight) pos.Y = textView.ActualHeight;
            pos += textView.ScrollOffset;
            if (pos.Y > textView.DocumentHeight) pos.Y = textView.DocumentHeight;<commit_msg>refactor<commit_after>﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using ICSharpCode.AvalonEdit;
using MarkdownEdit.ImageUpload;

namespace MarkdownEdit.Controls
{
    public partial class ImageDropDialog
    {
        public TextEditor TextEditor { get; set; }
        public DragEventArgs DragEventArgs { get; set; }
        private bool _canceled;

        public ImageDropDialog()
        {
            InitializeComponent();
            Activated += OnActivated;
        }

        private void OnActivated(object sender, EventArgs eventArgs)
        {
            var position = DragEventArgs.GetPosition(TextEditor);
            var screen = new Point(position.X, position.Y);
            Left = screen.X;
            Top = screen.Y;
        }

        private void OnInsertPath(object sender, RoutedEventArgs e)
        {
            var files = DragEventArgs.Data.GetData(DataFormats.FileDrop) as string[];
            if (files == null) return;
            var file = Path.GetFileNameWithoutExtension(files[0]);
            var path = Uri.EscapeUriString(files[0].Replace('\\', '/'));
            if (path.Contains(":")) path = "file:" + path;
            InsertImageLink(path, file);
            Close();
        }

        private void OnUploadToImgur(object sender, RoutedEventArgs e)
        {
            var files = DragEventArgs.Data.GetData(DataFormats.FileDrop) as string[];
            if (files == null) return;
            var path = files[0];
            var name = Path.GetFileNameWithoutExtension(path);

            UploadProgressChangedEventHandler progress = (o, args) => TextEditor.Dispatcher.InvokeAsync(() =>
            {
                if (_canceled) ((WebClient)o).CancelAsync();
                var progressPercentage = (int)((args.BytesSent / (double)args.TotalBytesToSend) * 100);
                ImgurMenuItem.Header = (progressPercentage == 100) ? "Processing" : $"{progressPercentage}%";
            });

            UploadValuesCompletedEventHandler completed = (o, args) => { if (_canceled) ((WebClient)o).CancelAsync(); };

            Action<string, string> processResult = (link, description) =>
            {
                if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
                {
                    InsertImageLink(link, description);
                }
                else
                {
                    MessageBox.Show(link, App.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            };

            new ImageUploadImgur()
                .UploadBytesAsync(File.ReadAllBytes(path), progress, completed)
                .ContinueWith(task => TextEditor.Dispatcher.InvokeAsync(() => processResult(task.Result, name)))
                .ContinueWith(task => Dispatcher.InvokeAsync(Close));
        }

        private void OnCancel(object sender, RoutedEventArgs e)
        {
            _canceled = true;
            Close();
        }

        private void InsertImageLink(string link, string description)
        {
            TextEditor.Document.Insert(GetInsertOffset(), $"![{description}]({link})\n");
        }

        private int GetInsertOffset()
        {
            var position = DragEventArgs.GetPosition(TextEditor);
            var offset = GetOffsetFromMousePosition(TextEditor, position);
            if (offset == -1) offset = TextEditor.Document.TextLength;
            return offset;
        }

        private static int GetOffsetFromMousePosition(TextEditor textEditor, Point positionRelativeToTextView)
        {
            var textView = textEditor.TextArea.TextView;
            var pos = positionRelativeToTextView;
            if (pos.Y < 0) pos.Y = 0;
            if (pos.Y > textView.ActualHeight) pos.Y = textView.ActualHeight;
            pos += textView.ScrollOffset;
            if (pos.Y > textView.DocumentHeight) pos.Y = textView.DocumentHeight;
{'fraction_non_alphanumeric': 0.10067800946654727, 'fraction_numerical': 0.0030702315466291418, 'mean_word_length': 1.968109339407745, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5101178', 'n_tokens_mistral': 2028, 'n_tokens_neox': 1945, 'n_words': 433}