using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
//using System.Windows.Shapes;
using WpfApp1.Structure;
using WpfApp1.Tools;
using static System.Formats.Asn1.AsnWriter;
using System.Xml.Linq;
using Emgu.CV.Structure;
using Emgu.CV;
using Emgu.CV.Util;
using Emgu.CV.CvEnum;
using System.Drawing;
using Microsoft.Win32;
using System.IO;
using System.Text.Json;
using System.Windows.Media.Media3D;
using System.Diagnostics;
using System.Security.Cryptography.Xml;
using System.Windows.Controls.Primitives;
using static Emgu.Util.Platform;
using static System.Net.Mime.MediaTypeNames;
using System.Windows.Threading;
//using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(Keyboard.Modifiers == ModifierKeys.Control))
            {
                return;
            }
            if (e.Key == Key.T)
            {
                //RelayoutOverlappingNode(GetSelectedSymbol() as Node);

                //MoveSymbol(d_idSymbol[1], -60, 0);

                //IdListBox_t.Items.Clear();
                //foreach (Symbol symbol in currentSymbols)
                //{
                //    ListBoxItem item = new ListBoxItem();
                //    item.Content = "id: " + symbol.id.ToString() + "  " + symbol.text;
                //    //item.Background = new SolidColorBrush(SymbolColor.d_Colors[symbol.color]);
                //    item.Background = new SolidColorBrush(LightColor(SymbolColor.d_Colors[symbol.color], 0.3, 0.3));
                //    item.Tag = symbol.id;
                //    item.BorderBrush = Brushes.White;
                //    item.BorderThickness = new Thickness(2);
                //    item.Padding = new Thickness(5);
                //    IdListBox_t.Items.Add(item);
                //}

                Symbol symbol = GetSelectedSymbol();
                StylusPointCollection points = new StylusPointCollection();

                int segments = 100; // 圆形的分段数
                double step = 2 * Math.PI / segments; // 每个分段的弧度步长

                for (int i = 0; i <= segments; i++)
                {
                    double angle = i * step;
                    double x = symbol.center[0] + 70 * Math.Cos(angle);
                    double y = symbol.center[1] + 70 * Math.Sin(angle);

                    points.Add(new StylusPoint(x, y));
                }

                symbol.strokes[0].StylusPoints = points;
                symbol.strokes[0].DrawingAttributes.Color = Colors.Red;
            }
            else if (e.Key == Key.B)
            {
                //MoveSymbol(d_idSymbol[1], 60, 0);

                Symbol symbol = GetSelectedSymbol();
                StylusPointCollection points = new StylusPointCollection();

                double x1 = symbol.center[0];
                double y1 = symbol.center[1] - 70;

                double x2 = symbol.center[0] - 60.62;
                double y2 = symbol.center[1] + 35;

                double x3 = symbol.center[0] + 60.62;
                double y3 = symbol.center[1] + 35;

                points.Add(new StylusPoint(x1, y1));
                points.Add(new StylusPoint(x2, y2));
                points.Add(new StylusPoint(x3, y3));
                points.Add(new StylusPoint(x1, y1));

                symbol.strokes[0].StylusPoints = points;
                symbol.strokes[0].DrawingAttributes.Color = Colors.DarkOrchid;
            }
            else if (e.Key == Key.X)
            {
                Symbol symbol = GetSelectedSymbol();
                StylusPointCollection points = new StylusPointCollection();

                double x1 = symbol.center[0] - 50;
                double y1 = symbol.center[1] - 35;

                double x2 = symbol.center[0] + 50;
                double y2 = symbol.center[1] - 35;

                double x3 = symbol.center[0] + 20;
                double y3 = symbol.center[1] + 35;

                double x4 = symbol.center[0] - 80;
                double y4 = symbol.center[1] + 35;

                points.Add(new StylusPoint(x1, y1));
                points.Add(new StylusPoint(x2, y2));
                points.Add(new StylusPoint(x3, y3));
                points.Add(new StylusPoint(x4, y4));
                points.Add(new StylusPoint(x1, y1));

                symbol.strokes[0].StylusPoints = points;
                symbol.strokes[0].DrawingAttributes.Color = Colors.Orange;
            }
            else if (e.Key == Key.K)
            {
                //foreach (Symbol symbol in currentSymbols)
                //{
                //    //if (symbol is Node)
                //    {
                //        foreach (Stroke stroke in symbol.strokes)
                //        {
                //            stroke.StylusPoints = ApplyHandDrawnStyle(stroke.StylusPoints);
                //        }
                //    }
                //}
                foreach (Stroke stroke in video_sketch.Strokes)
                {
                    if (!d_StrokeSymbol.ContainsKey(stroke))
                    {
                        continue;
                    }
                    stroke.StylusPoints = ApplyHandDrawnStyle(stroke.StylusPoints);
                }
            }
            else if (e.Key == Key.R)
            {
                foreach (Symbol symbol in currentSymbols)
                {
                    symbol.Resized();
                    symbol.RefreshTextBox();
                }
            }
            else if (e.Key == Key.O)
            {
                MoveSymbol(d_idSymbol[1], -60, 0);
            }
            else if (e.Key == Key.P)
            {
                MoveSymbol(d_idSymbol[1], 60, 0);
            }
            else if (e.Key == Key.N)
            {
                Symbol te = GetSelectedSymbol();
                StrokeCollection strokes = new StrokeCollection();
                bool tb = true;
                foreach (Stroke stroke in te.strokes)
                {
                    stroke.DrawingAttributes.IsHighlighter = true;
                    if (!tb)
                    {
                        strokes.Add(stroke);
                        continue;
                    }
                    tb = false;
                    stroke.StylusPoints = ApplyBezierCurveInterpolation(stroke.StylusPoints, 0.2);
                    stroke.StylusPoints = ApplyBezierCurveInterpolation(stroke.StylusPoints, 3);
                    strokes.Add(CreateDashedStrokes(stroke));
                }
                foreach (Stroke stroke in strokes)
                {
                    if (!d_StrokeSymbol.ContainsKey(stroke))
                    {
                        d_StrokeSymbol.Add(stroke, te);
                    }
                }
                video_sketch.Strokes.Remove(te.strokes);
                te.strokes = strokes;
                video_sketch.Strokes.Add(te.strokes);
            }
            else if (e.Key == Key.M)
            {
                Symbol te = GetSelectedSymbol();
                StrokeCollection strokes = new StrokeCollection();
                bool tb = true;
                foreach (Stroke stroke in te.strokes)
                {
                    stroke.DrawingAttributes.Color = SymbolColor.d_Colors["gray"];
                    if (!tb)
                    {
                        strokes.Add(stroke);
                        continue;
                    }
                    tb = false;
                    stroke.StylusPoints = ApplyBezierCurveInterpolation(stroke.StylusPoints, 0.2);
                    stroke.StylusPoints = ApplyBezierCurveInterpolation(stroke.StylusPoints, 3);
                    strokes.Add(CreateDashedStrokes(stroke));
                }
                video_sketch.Strokes.Remove(te.strokes);
                te.strokes = strokes;
                video_sketch.Strokes.Add(te.strokes);
            }
            else if (e.Key == Key.W)
            {
                foreach (Symbol symbol in currentSymbols)
                {
                    if (symbol is Edge)
                    {
                        symbol.SetCategory("Arrow");
                        foreach (Stroke stroke in symbol.strokes)
                        {
                            if (!video_sketch.Strokes.Contains(stroke))
                            {
                                video_sketch.Strokes.Add(stroke);
                            }
                        }
                    }
                }
            }
            else if (e.Key == Key.J)
            {
                StrokeCollection strokes = video_sketch.GetSelectedStrokes().Clone();
                Matrix matrix = new Matrix();
                matrix.Translate(100, 0);
                matrix.RotateAt(-90, strokes.GetBounds().Left, strokes.GetBounds().Top);
                foreach (Stroke stroke in strokes)
                {
                    stroke.Transform(matrix, false);
                }
                video_sketch.Strokes.Add(strokes);
            }
            else if (e.Key == Key.I)
            {
                StrokeCollection strokes = new StrokeCollection();
                foreach (Stroke stroke in video_sketch.Strokes)
                {
                    StylusPointCollection stylusPoints = new StylusPointCollection();
                    foreach (StylusPoint stylusPoint in stroke.StylusPoints)
                    {
                        stylusPoints.Add(new StylusPoint(stylusPoint.X, stylusPoint.Y));
                    }
                    strokes.Add(new Stroke(stylusPoints));
                }
                video_sketch.Strokes.Clear();
                video_sketch.Strokes.Add(strokes);
            }
            else if (e.Key == Key.L)
            {
                List<object> root = new List<object>();
                foreach (Stroke stroke in video_sketch.Strokes)
                {
                    List<int[]> ints = new List<int[]>();
                    foreach (StylusPoint strokePoint in stroke.StylusPoints)
                    {
                        ints.Add(new int[2] { (int)strokePoint.X, (int)strokePoint.Y });
                    }
                    root.Add(ints.ToArray());
                }
                string json = JsonSerializer.Serialize(root);
                File.WriteAllText("D:\\Project\\GPH\\WpfApp1\\WpfApp1\\test.json", JsonSerializer.Serialize(root), Encoding.UTF8);
            }
            else if (e.Key == Key.G)
            {
                Edge edge = AddEdge("", "", "", 0, 500, 500, 300, 500);
                StylusPointCollection stylusPoints = new StylusPointCollection
                {
                    new StylusPoint(500, 500),
                    new StylusPoint(500, 700),
                    new StylusPoint(300, 700),
                    new StylusPoint(300, 500)
                };
                edge.strokes[0].StylusPoints = stylusPoints;
                Edge edge2 = AddEdge("", "", "", 0, 500, 500, 300, 500);
                StylusPointCollection stylusPoints2 = new StylusPointCollection
                {
                    new StylusPoint(800, 500),
                    new StylusPoint(900, 500),
                    new StylusPoint(900, 700)
                };
                edge2.strokes[0].StylusPoints = stylusPoints2;
                Edge edge3 = AddEdge("", "", "", 0, 500, 500, 300, 500);
                Edge edge4 = AddEdge("", "", "", 0, 500, 600, 300, 600);
                Edge edge5 = AddEdge("", "", "", 0, 500, 700, 300, 700);
            }
            else if (e.Key == Key.H)
            {
                StrokeCollection strokes = new StrokeCollection();
                foreach (Stroke stroke in video_sketch.GetSelectedStrokes())
                {
                    stroke.DrawingAttributes.Color = SymbolColor.d_Colors["gray"];
                    strokes.Add(CreateDashedStrokes(stroke));
                }
                video_sketch.Strokes.Remove(video_sketch.GetSelectedStrokes());
                video_sketch.Strokes.Add(strokes);
            }
            else if (e.Key == Key.Y)
            {
                foreach (Stroke stroke in video_sketch.Strokes)
                {
                    stroke.DrawingAttributes.Width = 3;
                    stroke.DrawingAttributes.Height = 3;
                }
            }
        }

        private void cb_node_DropDownOpened(object sender, EventArgs e)
        {
            RefreshNodeList();
        }

        private void cb_edge_DropDownOpened(object sender, EventArgs e)
        {
            RefreshEdgeList();
        }

        private void cb_node_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ShowNodeItems(cb_node.SelectedItem as Node);
            sp_edge.Background = null;
            //sp_node.Background = new SolidColorBrush(Colors.MediumSpringGreen);
        }

        private void cb_edge_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ShowEdgeItems(cb_edge.SelectedItem as Edge);
            //sp_edge.Background = new SolidColorBrush(Colors.MediumSpringGreen);
            sp_node.Background = null;
        }

        //按钮
        private void btn_pen_Click(object sender, RoutedEventArgs e)
        {
            video_sketch.EditingMode = InkCanvasEditingMode.Ink;
        }

        private void btn_eraser_Click(object sender, RoutedEventArgs e)
        {
            video_sketch.EditingMode = InkCanvasEditingMode.EraseByStroke;
        }

        private void btn_selector_Click(object sender, RoutedEventArgs e)
        {
            video_sketch.EditingMode = InkCanvasEditingMode.Select;
        }

        private void btn_undo_Click(object sender, RoutedEventArgs e)
        {
            Undo();
        }

        private void btn_redo_Click(object sender, RoutedEventArgs e)
        {
            Redo();
        }

        private void btn_open_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Title = "打开文件",
                InitialDirectory = AppContext.BaseDirectory,
                Filter = "Json/Isf files (*.json;*.isf)|*.json;*.isf|All files (*.*)|*.*",
                FilterIndex = 1,
                RestoreDirectory = true
            };
            if (openFileDialog.ShowDialog() == true)
            {
                string filePath = openFileDialog.FileName;
                //ClearAll();
                LoadAll(Path.GetFileNameWithoutExtension(filePath));
                //switch (Path.GetExtension(filePath))
                //{
                //    case ".json":
                //        string json = File.ReadAllText(filePath, Encoding.UTF8);
                //        LoadJson(json);
                //        break;
                //    case ".isf":
                //        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                //        //video_sketch.Strokes = new StrokeCollection(fileStream);
                //        video_sketch.Strokes.Add(new StrokeCollection(fileStream));
                //        fileStream.Close();
                //        break;
                //}
            }
        }

        private void btn_save_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Title = "保存文件",
                InitialDirectory = AppContext.BaseDirectory,
                Filter = "Json files (*.json)|*.json|Isf files (*.isf)|*.isf|All files (*.*)|*.*",
                FilterIndex = 1,
                RestoreDirectory = true
            };
            if (saveFileDialog.ShowDialog() == true)
            {
                string filePath = saveFileDialog.FileName;
                SaveAll(Path.GetFileNameWithoutExtension(filePath));
                //switch (Path.GetExtension(filePath))
                //{
                //    case ".json":
                //        string json = SaveJson();
                //        File.WriteAllText(filePath, json, Encoding.UTF8);
                //        break;
                //    case ".isf":
                //        FileStream fileStream = new FileStream(filePath, FileMode.Create);
                //        video_sketch.Strokes.Save(fileStream);
                //        fileStream.Close();
                //        break;
                //}
            }
        }
        private void btn_mic_Click(object sender, RoutedEventArgs e)
        {
            //ScaleTransform scaleTransform = new ScaleTransform(0.5, 0.5);
            //this.LayoutTransform = scaleTransform;
            //tsymbols = LoadSymbols("test2");
            //foreach (Symbol symbol in tsymbols)
            //{
            //    video_sketch.Strokes.Add(symbol.strokes);
            //}
            gd_col1.Margin = new Thickness(gd_col1.Margin.Left, gd_col1.Margin.Top - 10, gd_col1.Margin.Right, gd_col1.Margin.Bottom);
        }

        private void btn_upload_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Title = "打开文件",
                InitialDirectory = "C:\\Users\\supersonic\\Desktop\\test",
                Filter = "All files (*.*)|*.*",
                FilterIndex = 1,
                RestoreDirectory = true
            };
            if (openFileDialog.ShowDialog() == true)
            {
                tb_input.Text += "\n[file:" + Path.GetFileName(openFileDialog.FileName) + "]";
            }
        }

        private void btn_send_Click(object sender, RoutedEventArgs e)
        {
            //SendTalk();
            SendTest();
        }

        private void btn_yes_Click(object sender, RoutedEventArgs e)
        {
            RemoveShadowStrokes();
            //sp_check.Visibility = Visibility.Hidden;
            pp_check.IsOpen = false;
        }

        private void btn_no_Click(object sender, RoutedEventArgs e)
        {
            ReturnShadowStrokes();
            //sp_check.Visibility = Visibility.Hidden;
            pp_check.IsOpen = false;
        }

        private void btn_hide_left_Click(object sender, RoutedEventArgs e)
        {
            if (hide_left)
            {
                col1_1.Visibility = Visibility.Visible;
                col1.Width = GridLength.Auto;
                col2.Width = new GridLength(1, GridUnitType.Star);
                hide_left = !hide_left;
            }
            else
            {
                col1_1.Visibility = Visibility.Collapsed;
                col1.Width = GridLength.Auto;
                col2.Width = new GridLength(1, GridUnitType.Star);
                hide_left = !hide_left;
            }
        }

        private void btn_hide_right_Click(object sender, RoutedEventArgs e)
        {
            if (hide_right)
            {
                col3_2.Visibility = Visibility.Visible;
                col3.Width = new GridLength(360);
                col2.Width = new GridLength(1, GridUnitType.Star);
                hide_right = !hide_right;
            }
            else
            {
                col3_2.Visibility = Visibility.Collapsed;
                col3.Width = GridLength.Auto;
                col2.Width = new GridLength(1, GridUnitType.Star);
                hide_right = !hide_right;
            }
        }

        //文本框
        private void tb_code_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return || e.Key == Key.Enter)
            {
                e.Handled = true;
                CheckCode();
            }
        }

        private void tb_input_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return || e.Key == Key.Enter)
            {
                e.Handled = true;
                SendTalk();
            }
        }

        //工具栏
        private void th_tools_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            th_tools.Margin = new Thickness(th_tools.Margin.Left + e.HorizontalChange, th_tools.Margin.Top + e.VerticalChange, 0, 0);
        }

        private void th_agent_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            th_agent.Margin = new Thickness(th_agent.Margin.Left + e.HorizontalChange, th_agent.Margin.Top + e.VerticalChange, 0, 0);
        }

        private void th_tools_LostFocus(object sender, RoutedEventArgs e)
        {
            FrameworkElement focusedElement = FocusManager.GetFocusedElement(this) as FrameworkElement;
            if (focusedElement != null && IsChildOf(focusedElement, th_tools))
            {
                return;
            }
            //th_tools.Visibility = Visibility.Hidden;
        }

        private void th_agent_LostFocus(object sender, RoutedEventArgs e)
        {
            FrameworkElement focusedElement = FocusManager.GetFocusedElement(this) as FrameworkElement;
            if (focusedElement != null && IsChildOf(focusedElement, th_agent))
            {
                return;
            }
            th_agent.Visibility = Visibility.Hidden;
        }

        private void tool_copy_Click(object sender, RoutedEventArgs e)
        {
            Symbol? symbol = GetSelectedSymbol();
            if (symbol != null)
            {
                previousSelectedSymbol = symbol;
            }
        }

        private void tool_cut_Click(object sender, RoutedEventArgs e)
        {
            Symbol? symbol = GetSelectedSymbol();
            if (symbol != null)
            {
                previousSelectedSymbol = symbol;
                DeleteSymbol(symbol);
            }
        }

        private void tool_paste_Click(object sender, RoutedEventArgs e)
        {
            Symbol pastedSymbol = previousSelectedSymbol.Clone();
            //触发SizeChanged
            pastedSymbol.text_box.Visibility = Visibility.Hidden;
            pastedSymbol.id = ++Symbol_id;
            d_idSymbol.Add(Symbol_id, pastedSymbol);
            foreach (Stroke stroke in pastedSymbol.strokes)
            {
                d_idStroke.Add(++Stroke_id, stroke);
                d_StrokeSymbol.Add(stroke, pastedSymbol);
            }

            double centerX, centerY;
            Symbol? symbol = GetSelectedSymbol();
            if (symbol != null)
            {
                centerX = symbol.center[0] + 250;
                centerY = symbol.center[1] - 150;
                MoveSymbol(pastedSymbol, centerX - pastedSymbol.center[0], centerY - pastedSymbol.center[1]);
                if (symbol is Node && pastedSymbol is Node)
                {
                    AddEdgeBetweenNodes(symbol as Node, pastedSymbol as Node);
                }
            }
            else
            {
                centerX = th_tools.Margin.Left;
                centerY = th_tools.Margin.Bottom;
                MoveSymbol(pastedSymbol, centerX - pastedSymbol.center[0], centerY - pastedSymbol.center[1]);
            }

            video_sketch.Strokes.Add(pastedSymbol.strokes);
            pastedSymbol.text_box.Visibility = Visibility.Visible;
            currentSymbols.Add(pastedSymbol);
        }

        private void tool_delete_Click(object sender, RoutedEventArgs e)
        {
            Symbol? symbol = GetSelectedSymbol();
            if (symbol != null)
            {
                DeleteSymbol(symbol);
            }
        }

        private void tool_insert_Click(object sender, RoutedEventArgs e)
        {
            Symbol? symbol = GetSelectedSymbol();
            if (symbol != null)
            {
                if (symbol is Node)
                {
                    AddNodeOfNode(symbol as Node, "Process");
                }
            }
        }

        private void tool_mark_Click(object sender, RoutedEventArgs e)
        {
            Symbol? symbol = GetSelectedSymbol();
            if (symbol != null)
            {
                if (markedSymbols.Contains(symbol))
                {
                    markedSymbols.Remove(symbol);
                }
                else
                {
                    markedSymbols.Add(symbol);
                }
            }
        }

        private void tool_fold_Click(object sender, RoutedEventArgs e)
        {

        }

        private void tool_unfold_Click(object sender, RoutedEventArgs e)
        {

        }

        private void tool_deleteTree_Click(object sender, RoutedEventArgs e)
        {

        }

        private void tool_reverse_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void tool_insertBranch_Click(object sender, RoutedEventArgs e)
        {

        }

        private void tool_changeClass_Click(object sender, RoutedEventArgs e)
        {
            CCListBox.Items.Clear();
            if (GetSelectedSymbol() is Node)
            {
                foreach (string category in nodeClassList)
                {
                    ListBoxItem item = new ListBoxItem();
                    item.Content = category;
                    item.Background = new SolidColorBrush(SymbolColor.d_Colors[SymbolColor.d_CategoryColor[category]]);
                    item.BorderBrush = Brushes.White;
                    item.BorderThickness = new Thickness(2);
                    item.Padding = new Thickness(5);
                    CCListBox.Items.Add(item);
                }
            }
            else if (GetSelectedSymbol() is Edge)
            {
                foreach (string category in edgeClassList)
                {
                    ListBoxItem item = new ListBoxItem();
                    item.Content = category;
                    item.Background = new SolidColorBrush(SymbolColor.d_Colors[SymbolColor.d_CategoryColor[category]]);
                    item.BorderBrush = Brushes.White;
                    item.BorderThickness = new Thickness(2);
                    item.Padding = new Thickness(5);
                    CCListBox.Items.Add(item);
                }
            }
            CCPopup.PlacementTarget = sender as Button;
            CCPopup.HorizontalOffset = ((sender as Button).ActualWidth - 120) / 2;
            CCPopup.IsOpen = true;
        }

        //画板
        private void video_sketch_EditingModeChanged(object sender, RoutedEventArgs e)
        {

        }

        private void video_sketch_WheelChange(object sender, MouseWheelEventArgs e)
        {

        }
        private void video_sketch_SelectionChanging(object sender, InkCanvasSelectionChangingEventArgs e)
        {

        }

        private void video_sketch_SelectionChanged(object sender, EventArgs e)
        {
            //return;
            Symbol? symbol = GetSelectedSymbol();
            if (symbol == null)
            {
                sp_node.Background = null;
                sp_edge.Background = null;
                //img_test.Visibility = Visibility.Hidden;
                //img_test2.Visibility = Visibility.Hidden;
                //img_test2.Source = new BitmapImage(new Uri(basePath + "Jeju2.png"));
                //img_test3.Visibility = Visibility.Hidden;
                foreach (Symbol tsymbol in tsymbols1)
                {
                    if (tsymbol.text_thumb.Visibility == Visibility.Visible)
                    {
                        tsymbol.text_thumb.Visibility = Visibility.Hidden;
                        video_sketch.Strokes.Remove(tsymbol.strokes);
                    }
                }
                foreach (Symbol tsymbol in tsymbols2)
                {
                    if (tsymbol.text_thumb.Visibility == Visibility.Visible)
                    {
                        tsymbol.text_thumb.Visibility = Visibility.Hidden;
                        video_sketch.Strokes.Remove(tsymbol.strokes);
                    }
                }
                return;
            }
            video_sketch.Select(symbol.strokes);

            if (symbol.text == "Jeongbang Falls")
            {
                img_test.Source = new BitmapImage(new Uri(basePath + "Jeju2.png"));
                img_test2.Source = new BitmapImage(new Uri(basePath + "map1.png"));
                //img_test3.Source = new BitmapImage(new Uri(basePath + "att1.png"));
                img_test.Visibility = Visibility.Visible;
                img_test2.Visibility = Visibility.Visible;
                //img_test3.Visibility = Visibility.Visible;
                foreach (Symbol tsymbol in tsymbols1)
                {
                    if (tsymbol.text_thumb.Visibility == Visibility.Hidden)
                    {
                        tsymbol.text_thumb.Visibility = Visibility.Visible;
                        video_sketch.Strokes.Add(tsymbol.strokes);
                    }
                }
                foreach (Symbol tsymbol in tsymbols2)
                {
                    if (tsymbol.text_thumb.Visibility == Visibility.Visible)
                    {
                        tsymbol.text_thumb.Visibility = Visibility.Hidden;
                        video_sketch.Strokes.Remove(tsymbol.strokes);
                    }
                }
            }
            else if (symbol.text == "Seongeup Folk Village")
            {
                img_test.Source = new BitmapImage(new Uri(basePath + "Jeju2.png"));
                img_test2.Source = new BitmapImage(new Uri(basePath + "map2.png"));
                //img_test3.Source = new BitmapImage(new Uri(basePath + "att2.png"));
                img_test.Visibility = Visibility.Visible;
                img_test2.Visibility = Visibility.Visible;
                //img_test3.Visibility = Visibility.Visible;
                foreach (Symbol tsymbol in tsymbols2)
                {
                    if (tsymbol.text_thumb.Visibility == Visibility.Hidden)
                    {
                        tsymbol.text_thumb.Visibility = Visibility.Visible;
                        video_sketch.Strokes.Add(tsymbol.strokes);
                    }
                }
                foreach (Symbol tsymbol in tsymbols1)
                {
                    if (tsymbol.text_thumb.Visibility == Visibility.Visible)
                    {
                        tsymbol.text_thumb.Visibility = Visibility.Hidden;
                        video_sketch.Strokes.Remove(tsymbol.strokes);
                    }
                }
            }
            else
            {
                //img_test.Visibility = Visibility.Hidden;
                //img_test2.Visibility = Visibility.Hidden;
                //img_test3.Visibility = Visibility.Hidden;
            }

            RefreshNodeList();
            RefreshEdgeList();
            if (symbol is Node)
            {
                cb_node.SelectedItem = symbol as Node;
            }
            else if (symbol is Edge)
            {
                cb_edge.SelectedItem = symbol as Edge;
            }
            Rect selectedBounds = video_sketch.GetSelectionBounds();

            switch (symbol.category)
            {
                case "Arrow":
                    th_tools.Template = this.FindResource("arrowTools") as ControlTemplate;
                    break;
                case "Process":
                    th_tools.Template = this.FindResource("processTools") as ControlTemplate;
                    break;
                case "Decision":
                    th_tools.Template = this.FindResource("decisionTools") as ControlTemplate;
                    break;
                default:
                    th_tools.Template = this.FindResource("defaultTools") as ControlTemplate;
                    break;
            }
            th_tools.Margin = new Thickness(selectedBounds.Right - th_tools.ActualWidth / 2, selectedBounds.Top - th_tools.ActualHeight - 15, 0, 0);
            th_tools.Visibility = Visibility.Visible;
            th_tools.Focus();
            //th_agent.Margin = new Thickness(selectedBounds.Right - selectedBounds.Width / 2 - th_agent.ActualWidth / 2, selectedBounds.Bottom + 10, 0, 0);
            //th_agent.Visibility = Visibility.Visible;
            //th_agent.Focus();

            string inputText = tb_input.Text;
            if (!string.IsNullOrEmpty(inputText) && inputText.Last() == '@')
            {
                tb_input.Text += symbol.id.ToString();
            }
        }


        private void video_sketch_SelectionMoving(object sender, InkCanvasSelectionEditingEventArgs e)
        {
            previousSelectionBounds = e.OldRectangle;
        }

        private void video_sketch_SelectionMoved(object sender, EventArgs e)
        {
            Rect currentBounds = video_sketch.GetSelectionBounds();
            double movedDistanceX = currentBounds.Left - previousSelectionBounds.Left;
            double movedDistanceY = currentBounds.Top - previousSelectionBounds.Top;

            Stroke selectedStroke = video_sketch.GetSelectedStrokes()[0];
            if (d_StrokeSymbol.ContainsKey(selectedStroke))
            {
                Symbol selectedSymbol = d_StrokeSymbol[selectedStroke];
                PushHistory(new History("MoveSymbol", new Dictionary<string, object> { { "symbol", selectedSymbol }, { "movedDistanceX", movedDistanceX }, { "movedDistanceY", movedDistanceY } }));
                useShadowSymbol = false;
                SymbolMoved(selectedSymbol, movedDistanceX, movedDistanceY);
                useShadowSymbol = true;
            }
        }

        private void video_sketch_SelectionResizing(object sender, InkCanvasSelectionEditingEventArgs e)
        {
            previousSelectionBounds = e.OldRectangle;
        }

        private void video_sketch_SelectionResized(object sender, EventArgs e)
        {
            Rect currentBounds = video_sketch.GetSelectionBounds();
            Stroke selectedStroke = video_sketch.GetSelectedStrokes()[0];
            if (d_StrokeSymbol.ContainsKey(selectedStroke))
            {
                Symbol selectedSymbol = d_StrokeSymbol[selectedStroke];
                PushHistory(new History("ResizeSymbol", new Dictionary<string, object> { { "symbol", selectedSymbol }, { "oldBounds", previousSelectionBounds }, { "bounds", currentBounds } }));
                useShadowSymbol = false;
                SymbolResized(selectedSymbol, previousSelectionBounds, currentBounds);
                useShadowSymbol = true;
            }
        }

        private void video_sketch_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
        {

        }

        private void video_sketch_StrokeErased(object sender, RoutedEventArgs e)
        {

        }

        private void video_sketch_StrokeErasing(object sender, InkCanvasStrokeErasingEventArgs e)
        {

        }
    }
}