MainForm.cs 40.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
using MoyaAdminLib;
using MoyaAdminUI.MoyaAPI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MoyaAdminUI
{
    public partial class MainForm : Form
    {
        int newPlaceHeight = 10;
        int newPlaceWidth = 10;
        Point clickedLocation;
        List<ComputerPlace> gridPreview = new List<ComputerPlace>();
        ComputerPlaceGridSettings gridSettingsForm;
        Size mouseDownOffset;
        ComputerPlace mouseDownComputerPlace;
        Point mouseDownPoint;
        Map SelectedMap;
        List<ComputerPlace> unsavedComputerPlaces = new List<ComputerPlace>();

        public MainForm()
        {
            InitializeComponent();
            RestClient.ApiApplicationKey = Properties.Settings.Default.ApiApplicationKey;
            RestClient.ApiPass = Properties.Settings.Default.ApiPass;
            RestClient.ApiUser = Properties.Settings.Default.ApiUser;
            RestClient.ApiURL = Properties.Settings.Default.ApiURL;

        }


        private void frmEditComputerPlace_Load(object sender, EventArgs e)
        {
            try
            {
                User.LoadAll();
                Map.LoadAll();
                loadPlacemap();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\nCannot connect to Moya.\r\nCheck Api url and key");
            }
            
        }

        private void loadPlacemap()
        {
            foreach (Map m in Map.Cache)
            {
                MapsComboBox.Items.Add(m);
            }
            if (MapsComboBox.Items.Count > 0)
            {
                MapsComboBox.SelectedItem = MapsComboBox.Items[0];
                loadComputerPlaces();
            }
            loadImage();
            
        }

        ComputerPlace selectedPlace;

        /// <summary>
        /// Loads computer places into listview from cache
        /// </summary>
        void loadComputerPlaces()
        {
            this.editComputerPlace(null);
            this.PlacesListView.Items.Clear();
            unsavedComputerPlaces.Clear();
            try
            {
                ComputerPlace.LoadAll(SelectedMap.Id);
                foreach (ComputerPlace place in ComputerPlace.Cache)
                {
                    addPlaceToListView(place);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Could not connect to Moya server");
            }
            MapPictureBox.Refresh();
        }

        void addPlaceToListView(ComputerPlace place)
        {
            ListViewItem li = new ListViewItem();
            li.Tag = place;
            li.Text = place.Name;
            li.SubItems.Add(place.ReserverUserName);
            li.SubItems.Add(place.MapX.ToString());
            li.SubItems.Add(place.MapY.ToString());
            this.PlacesListView.Items.Add(li);
        }


        void loadImage()
        {
            Size borderSize = this.Size - this.ClientSize;
            this.MapPictureBox.Load(RestClient.GetRequestURL(Properties.Settings.Default.ApiURL, "placeadmin/background/" + SelectedMap.Id));
            MapPictureBox.Size = this.MapPictureBox.Image.Size;
            panel2.Width = this.MapPictureBox.Image.Size.Width;
            this.MinimumSize = this.MapPictureBox.Image.Size + new Size(0, this.TopPanel.Size.Height + 20) + new Size(this.panel1.MinimumSize.Width + 270, 0) + borderSize;
        }


        private void MapPictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            clickedLocation = e.Location;
            if (e.Button == MouseButtons.Right)
            {
                ContextMenu menu = new ContextMenu();
                ComputerPlace computerPlace = findPlace(clickedLocation);

                //Creating menuitems
                MenuItem mi;



                mi = new MenuItem("Create a new computer place...", new EventHandler(this.createNewComputerPlace));
                mi.Enabled = (computerPlace == null);
                menu.MenuItems.Add(mi);

                mi = new MenuItem("Create a grid of new computer places...", new EventHandler(this.createNewComputerPlaceGrid));
                mi.Enabled = (computerPlace == null);
                menu.MenuItems.Add(mi);

                mi = new MenuItem("Select all in same group", new EventHandler(this.selectAllInGroup));
                mi.Enabled = (computerPlace != null);
                menu.MenuItems.Add(mi);

                mi = new MenuItem("Release selected (" + this.PlacesListView.SelectedItems.Count + ")", new EventHandler(this.releaseComputerPlace));
                mi.Enabled = (computerPlace != null);
                menu.MenuItems.Add(mi);

                mi = new MenuItem("Reserve selected (" + this.PlacesListView.SelectedItems.Count + ")", new EventHandler(this.reservePlaces));
                mi.Enabled = (computerPlace != null);
                menu.MenuItems.Add(mi);

                mi = new MenuItem("Delete selected permanently from database (" + this.PlacesListView.SelectedItems.Count + ")", new EventHandler(this.deleteMenuItemClick));
                mi.Enabled = (computerPlace != null);
                menu.MenuItems.Add(mi);

                mi = new MenuItem("Show buyer info", new EventHandler(this.showBuyerInfo));
                mi.Enabled = (computerPlace == null);
                menu.MenuItems.Add(mi);

                menu.Show(this.MapPictureBox, clickedLocation);
            }
            else if (e.Button == MouseButtons.Left && multiMoveLastLocation == null)
            {
                if (selectedPlace == findPlace(clickedLocation))
                {

                    ComputerPlace computerPlace = findPlace(clickedLocation);
                    if (computerPlace != null)
                    {
                        this.selectedPlace = computerPlace;
                        editComputerPlace(selectedPlace);
                    }
                    else
                    {
                        if (this.gridSettingsForm != null)
                        {
                            this.gridSettingsForm.ResendPreview();
                        }
                        if (mouseDownPoint == e.Location)
                        {
                            //clear selection if cursor didn't move
                            editComputerPlace(null);

                        }
                    }
                }
            }
            else if (e.Button == MouseButtons.Left && multiMoveLastLocation != null)
            {
                //multimove ended
                foreach (ListViewItem li in this.PlacesListView.SelectedItems)
                {
                    ComputerPlace p = (ComputerPlace)li.Tag;
                    if (!this.unsavedComputerPlaces.Contains(p))
                    {
                        this.unsavedComputerPlaces.Add(p);
                    }
                    changed();
                }
            }


            
            editObjects();
            
            mouseDownComputerPlace = null;
            multiSelectStart = null;
            multiSelectEnd = null;
            multiMoveLastLocation = null;
            this.MapPictureBox.Refresh();
        }



        private void selectAllInGroup(object sender, EventArgs e)
        {
            if (selectedPlace != null && selectedPlace.ReserverId > 0)
            {
                foreach (ListViewItem lvi in PlacesListView.Items)
                {
                    if (((ComputerPlace)lvi.Tag).ReserverId == selectedPlace.ReserverId)
                        lvi.Selected = true;
                }
            }
        }

        private void releaseComputerPlace(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, "Do you really want kick users from selected places", "Kick users?", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                foreach (ListViewItem li in this.PlacesListView.SelectedItems)
                {
                    ComputerPlace p = (ComputerPlace)li.Tag;
                    p.Release();
                }
                loadComputerPlaces();

            }
        }
        private void reservePlaces(object sender, EventArgs e)
        {

            foreach (ListViewItem li in this.PlacesListView.SelectedItems)
            {
                ComputerPlace p = (ComputerPlace)li.Tag;
                if (p.Taken)
                {
                    MessageBox.Show("Release places first");
                    return;
                }
            }
            UsersFinderForm frm = new UsersFinderForm();
            frm.AllowMultiSelect = false;
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                foreach (ListViewItem li in this.PlacesListView.SelectedItems)
                {
                    ComputerPlace p = (ComputerPlace)li.Tag;
                    
                    p.Reserve(frm.SelectedUser);
                }

                loadComputerPlaces();
            }

        }

        /// <summary>
        /// Finds a matching computer place for location clicked on picturebox.
        /// </summary>
        /// <param name="location"></param>
        /// <returns>ID of computer place or 0 if not found</returns>
        ComputerPlace findPlace(Point location)
        {
            foreach (ComputerPlace place in ComputerPlace.Cache)
            {
                if ((location.X >= place.MapX) &&
                    (location.Y >= place.MapY) &&
                    (location.X <= (place.MapX + place.Width)) &&
                    (location.Y <= (place.MapY + place.Height))
                    )
                {
                    return place;
                }
            }
            foreach (ComputerPlace place in this.unsavedComputerPlaces)
            {
                if ((location.X >= place.MapX) &&
                    (location.Y >= place.MapY) &&
                    (location.X <= (place.MapX + place.Width)) &&
                    (location.Y <= (place.MapY + place.Height))
                    )
                {
                    return place;
                }
            }
            return null;
        }

        ComputerPlace createComputerPlace(Point location)
        {

            ComputerPlace place = new ComputerPlace();
            place.MapId = SelectedMap.Id;
            place.ProductId = 262;
            this.unsavedComputerPlaces.Add(place);
            //place.Coord = location;
            place.MapX = location.X;
            place.MapY = location.Y;
            //place.Code = generateVerifiedCode();
            place.Name = "NEW";
            addPlaceToListView(place);
            MapPictureBox.Refresh();
            return place;
        }
        /*
        void updateGroupMenuItemClick(object sender, EventArgs e)
        {
            MenuItem mi = (MenuItem)sender;
            foreach (ListViewItem li in this.PlacesListView.SelectedItems)
            {
                ComputerPlace p = (ComputerPlace)li.Tag;
                if (mi.Tag == null)
                {
                    throw new Exception("mi.Tag == null");
                }
                else if (mi.Tag is int)
                {
                    
                    p.User = null;
                    //p.SpecialGroupId = (int)mi.Tag; WTF
                }
                    /* WTF???
                else if (mi.Tag is oGroup)
                {
                    //normal value (real ID)
                    //p.Group = (oGroup)mi.Tag; WTF
                }
                else
                {
                    throw new Exception("Unknown type for mi.Tag: " + mi.Tag.GetType().ToString());
                }
                if (!this.unsavedComputerPlaces.Contains(p))
                {
                    this.unsavedComputerPlaces.Add(p);
                }
            }
            this.toolStripSaveButton.Enabled = true;
        }
*/
        private void createNewComputerPlace(object sender, EventArgs e)
        {
            ComputerPlace place = createComputerPlace(clickedLocation);
            place.Width = newPlaceWidth;
            place.Height = newPlaceHeight;
            editComputerPlace(place);
            this.changed();
        }


        private void createNewComputerPlaceGrid(object sender, EventArgs e)
        {
            gridSettingsForm = new ComputerPlaceGridSettings();
            gridSettingsForm.PreviewAnswer += new ComputerPlaceGridSettingsAnswer(gridSettingsForm_PreviewAnswer);
            gridSettingsForm.AnswerGiven += new ComputerPlaceGridSettingsAnswer(gridSettingsForm_AnswerGiven);
            gridSettingsForm.Show(this);
        }

        void gridSettingsForm_AnswerGiven(bool cancel, int x, int y, bool ix, bool iy, string name, bool horizontalRow, int seatSpacing, int doubleRowSpacing)
        {
            List<ComputerPlace> returnList = new List<ComputerPlace>();
            this.gridPreview.Clear();
            if (!cancel)
            {
                addPlaceGrid(returnList, x, y, ix, iy, name, false, horizontalRow, seatSpacing, doubleRowSpacing);
                foreach (ComputerPlace p in returnList)
                {
                    unsavedComputerPlaces.Add(p);
                    addPlaceToListView(p);
                }
                this.editComputerPlace(returnList[returnList.Count - 1]); // get last    
                changed();
            }


            this.MapPictureBox.Refresh();
            this.gridSettingsForm = null;
        }

        void gridSettingsForm_PreviewAnswer(bool cancel, int x, int y, bool ix, bool iy, string name, bool horizontalRow, int seatSpacing, int doubleRowSpacing)
        {
            this.gridPreview.Clear();
            addPlaceGrid(gridPreview, x, y, ix, iy, name, true, horizontalRow, seatSpacing, doubleRowSpacing);
            this.MapPictureBox.Refresh();
        }

        void addPlaceGrid(List<ComputerPlace> list, int xcount, int ycount, bool ix, bool iy, string name, bool preview, bool horizontalRow, int seatSpacing, int doubleRowSpacing)
        {
            int dRowCount = -1;
            int count = 0;
            int x;
            if (ix)
            {
                //X is inverted (N...1)
                x = xcount;
            }
            else
            {
                //X is not inverted (1...N)
                x = 0;
            }

            if (ix && !horizontalRow)
                dRowCount = Convert.ToInt32(Math.Floor((double)(xcount / 2))) + 1;
            else if (iy && horizontalRow)
                dRowCount = Convert.ToInt32(Math.Floor((double)(ycount / 2))) + 1;


            int nameCount = -1;
            bool prefixList = false;
            string[] names = name.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (names.Length > 1)
            {
                if (xcount == names.Length)
                    prefixList = true;
                else if (ycount == names.Length)
                    prefixList = true;
            }

            while (true)
            {
                if (ix)
                {
                    if (x-- <= 0)
                        break;
                }
                else
                {
                    if (x++ >= xcount)
                        break;
                }

                int y;
                if (iy)
                {
                    //Y is inverted (N...1)
                    y = ycount;

                }
                else
                {
                    //Y is not inverted (1...N)
                    y = 0;
                    if (horizontalRow)
                        dRowCount = 0;
                }


                if (!horizontalRow)
                {
                    count = 0;
                    if (prefixList)
                        nameCount++;
                    if ((x % 2) != 0)
                    {
                        if (!ix)
                            dRowCount++;
                        else
                            dRowCount--;
                    }
                }
                else
                {
                    count++;
                    if (prefixList)
                        nameCount = -1;
                }

                while (true)
                {


                    if (iy)
                    {
                        if (y-- <= 0)
                            break;
                    }
                    else
                    {
                        if (y++ >= ycount)
                            break;
                    }

                    if (horizontalRow)
                    {
                        if (prefixList)
                            nameCount++;
                    }
                    else
                        count++;

                    if (prefixList)
                    {
                        if (xcount == names.Length && nameCount < names.Length && nameCount >= 0)
                        {
                            name = names[nameCount];
                        }
                        else if (ycount == names.Length && nameCount < names.Length && nameCount >= 0)
                        {
                            name = names[nameCount];
                        }
                    }

                    ComputerPlace p = new ComputerPlace();
                    p.MapId = SelectedMap.Id;
                    p.ProductId = 262;
                    p.Width = newPlaceWidth;
                    p.Height = newPlaceHeight;
                    int xcoord = 0;
                    int ycoord = 0;

                    if (horizontalRow)
                    {

                        // y modulo 2, Checking if y is non even.
                        if ((y % 2) != 0)
                        {
                            if (iy)
                                dRowCount--;
                            else
                                dRowCount++;
                        }
                        xcoord = x * (p.Width + seatSpacing) + clickedLocation.X;
                        ycoord = y * p.Height + dRowCount * doubleRowSpacing + clickedLocation.Y;
                    }
                    else
                    {
                        xcoord = x * p.Width + dRowCount * doubleRowSpacing + clickedLocation.X;
                        ycoord = y * (p.Height + seatSpacing) + clickedLocation.Y;
                    }

                    p.MapX = xcoord;
                    p.MapY = ycoord;
                    if (!preview)
                    {
                        p.Name = name + count;
                        //p.Code = generateVerifiedCode();
                    }
                    list.Add(p);
                }
            }
        }

        private void editComputerPlace(object sender, EventArgs e)
        {
            ComputerPlace computerPlace = findPlace(clickedLocation);
            if (computerPlace == null)
                throw new InvalidOperationException("findPlace(clickedLocation) returned null - shouldn't happen");
            editComputerPlace(computerPlace);

            //this.MapPictureBox.Refresh();
        }
        void editComputerPlace(ComputerPlace computerplace)
        {
            disableEvents = true;
            selectedPlace = computerplace;
            this.PlacesListView.SelectedItems.Clear();
            foreach (ListViewItem li in this.PlacesListView.Items)
            {
                if (li.Tag == computerplace)
                {
                    li.Selected = true;
                    li.EnsureVisible();
                    break;
                }
            }

            placeEditor.SelectedObject = computerplace;
            disableEvents = false;
            this.MapPictureBox.Refresh();
        }



        private void MapPictureBox_Paint(object sender, PaintEventArgs e)
        {
            //paint computer places
            unsafe
            {
                foreach (ComputerPlace place in ComputerPlace.Cache)
                {
                    paintPlace(e.Graphics, place, false);
                }

                foreach (ComputerPlace place in this.unsavedComputerPlaces)
                {
                    paintPlace(e.Graphics, place, false);
                }
                foreach (ComputerPlace place in this.gridPreview)
                {
                    paintPlace(e.Graphics, place, true);
                }
            }
            //paint selection area rectangle
            if (this.multiSelectStart != null && this.multiSelectEnd != null)
            {
                e.Graphics.DrawRectangle(
                    Pens.LightBlue,
                    new Rectangle(multiSelectStart.Value,
                    new Size(multiSelectEnd.Value.X - multiSelectStart.Value.X,
                            multiSelectEnd.Value.Y - multiSelectStart.Value.Y))
                            );
            }
        }

        void paintPlace(Graphics g, ComputerPlace place, bool forcePreviewColor)
        {
            Brush brush;
            if (forcePreviewColor)
            {
                brush = Brushes.Silver;
            }
            else if (place.Id == 0)
            {
                brush = Brushes.Purple;
            }
            else if (place.Taken)
            {
                if (place.APIReference.eventuserId > 0)
                    brush = Brushes.Green;
                else
                    brush = Brushes.Red;
            }
            else if (place.Buyable)
                brush = Brushes.White;
            else
            {
                brush = Brushes.Gray;
            }


            Rectangle r = new Rectangle(place.GetPoint(), place.GetSize());

            Pen pen;
            if (place == selectedPlace || isSelected(place))
            {
                pen = Pens.LightBlue;
            }
            else
            {
                pen = Pens.Black;
            }
            g.DrawRectangle(pen, new Rectangle(place.GetPoint(), place.GetSize() - new Size(1, 1)));
            g.FillRectangle(brush, new Rectangle(new Point(place.MapX + 1, place.MapY + 1), place.GetSize() - new Size(2, 2)));
        }

        bool isSelected(ComputerPlace p)
        {
            foreach (ListViewItem li in this.PlacesListView.SelectedItems)
            {
                if (li.Tag == p)
                    return true;
            }
            return false;
        }

        bool disableEvents = false;
        private void PlacesListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (disableEvents)
                return;

            if (this.PlacesListView.SelectedItems.Count == 0)
            {
                this.selectedPlace = null;
                placeEditor.SelectedObject = selectedPlace;
            }
            else if (this.PlacesListView.SelectedItems.Count == 1)
            {
                this.selectedPlace = (ComputerPlace)this.PlacesListView.SelectedItems[0].Tag;
                placeEditor.SelectedObject = selectedPlace;
            }

            ImageRefreshTimer.Start();
            
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {

        }
        bool checkSaveSafety()
        {
            string messages = "";
            foreach (ComputerPlace newplace in unsavedComputerPlaces)
            {
                foreach (ComputerPlace oldplace in ComputerPlace.Cache)
                {
                    if (newplace != oldplace)
                    {
                        if (newplace.Name.Trim().ToLower() == oldplace.Name.Trim().ToLower())
                        {
                            messages += "\r\nComputer place with name '" + newplace.Name + "' already exists.";
                        }
                    }
                }
            }
            if (messages != "")
            {
                MessageBox.Show("The following errors were detected:" + messages, "Saving cancelled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
            else
            {
                return true;
            }
        }
        void save()
        {
            if (!checkSaveSafety())
                return;
            this.toolStripSaveButton.Enabled = false;

            Application.DoEvents();
            this.Cursor = Cursors.WaitCursor;

            while (this.unsavedComputerPlaces.Count > 0)
            {
                ComputerPlace place = unsavedComputerPlaces[0];
                unsavedComputerPlaces.Remove(place);
                place.Save();
            }
            foreach (ComputerPlace cp in ComputerPlace.Cache)
            {
                if (cp.Dirty)
                    cp.Save();
            }
            this.MapPictureBox.Refresh();
            this.loadComputerPlaces();
            this.Cursor = Cursors.Default;
        }


        void changed()
        {
            if (disableEvents)
                return;

            if (!this.unsavedComputerPlaces.Contains(this.selectedPlace))
            {
                this.unsavedComputerPlaces.Add(this.selectedPlace);
            }
            this.toolStripSaveButton.Enabled = true;
            this.MapPictureBox.Refresh();
        }


        private void CloseButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmComputerPlaces_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.unsavedComputerPlaces.Count > 0)
            {
                DialogResult res = MessageBox.Show("There are unsaved changes. Do you want to close anyway and lose all changes?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res == DialogResult.No)
                {
                    e.Cancel = true;
                }
                else if (res == DialogResult.Yes)
                {
                    //reloading data for changed items from database
                    foreach (ComputerPlace place in unsavedComputerPlaces)
                    {
                        if (place.Id > 0)
                            place.Reload();
                    }
                }
            }
        }


        void deleteMenuItemClick(object sender, EventArgs e)
        {
            string placesList = "";
            foreach (ListViewItem li in this.PlacesListView.SelectedItems)
            {
                ComputerPlace p = (ComputerPlace)li.Tag;
                placesList += p.Name + " ";
            }
            DialogResult r = MessageBox.Show("Do you really want to permanently delete the following computer places?\r\n" + placesList, "Delete confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (r == DialogResult.Cancel)
                return;


            foreach (ListViewItem li in this.PlacesListView.SelectedItems)
            {
                ComputerPlace p = (ComputerPlace)li.Tag;
                if (p.Id > 0)
                {
                    p.Delete();
                }
                else
                {
                    if (this.unsavedComputerPlaces.Contains(p))
                    {
                        this.unsavedComputerPlaces.Remove(p);
                    }

                    foreach (ListViewItem li2 in this.PlacesListView.Items)
                    {
                        if (li2.Tag == p)
                        {
                            li2.Remove();
                        }
                    }
                }
            }

            this.MapPictureBox.Refresh();
        }
        /*
        void selectGroupMenuItemClick(object sender, EventArgs e)
        {
            MenuItem mi = (MenuItem)sender;
            if (mi.Tag == null)
            {
                throw new Exception("mi.Tag == null");
            }
            else if (mi.Tag is int)
            {
                //special value (not real ID)
                this.selectedPlace.User = null;
                // WTF??
                //this.selectedPlace.SpecialGroupId = (int) mi.Tag;
                placeEditor.SelectedObject = selectedPlace;
            }
                /* RLY?? WTF
            else if (mi.Tag is oGroup)
            {
                //normal value (real ID)
                this.selectedPlace.Group = (oGroup) mi.Tag;
                editComputerPlace(selectedPlace);
            }
                /
            else
            {
                throw new Exception("Unknown type for mi.Tag: " + mi.Tag.GetType().ToString());
            }

        }*/



        private void MapPictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseDownPoint = e.Location;
                mouseDownComputerPlace = findPlace(mouseDownPoint);
                //if (UnlockToolStripButton.Checked)
                //{
                    if (mouseDownComputerPlace != null)
                    {
                        //editComputerPlace(mouseDownComputerPlace);
                        selectedPlace = mouseDownComputerPlace;
                        mouseDownOffset = new Size(
                            e.Location.X - mouseDownComputerPlace.MapX,
                            e.Location.Y - mouseDownComputerPlace.MapY
                            );
                        newPlaceHeight = mouseDownComputerPlace.Height;
                        newPlaceWidth = mouseDownComputerPlace.Width;
                    }
                    else
                    {
                        editComputerPlace(null);
                    }
                //}
            }
        }

        Nullable<Point> multiSelectStart;
        Nullable<Point> multiSelectEnd;
        /// <summary>
        /// Where the mouse cursor was during last MouseMove event when moving
        /// multiple objects.
        /// </summary>
        Nullable<Point> multiMoveLastLocation;
        int inDistance(int A, int B)
        {
            if (A - B > B - A)
                return A - B;
            else
                return B - A;
        }

        int calculateDistance(int A, int B)
        {
            return B - A;
        }
        int nearest(int A, int B)
        {
            int outA = A;
            int outB = B;
            if (A < 0)
                A = 0 - A;
            if (B < 0)
                B = 0 - B;
            if (A < B)
                return outA;
            else return outB;
        }
        private void MapPictureBox_MouseMove(object sender, MouseEventArgs e)
        {

            
            
            unsafe
            {
                // if drag start top of place then move
                if (UnlockToolStripButton.Checked && e.Button == MouseButtons.Left && mouseDownComputerPlace != null)
                {
                    //drag & drop

                    //multimove

                    //Calculating difference from last movement
                    Size difference;
                    if (multiMoveLastLocation == null)
                    {
                        difference = new Size(
                            e.Location.X - mouseDownPoint.X,
                            e.Location.Y - mouseDownPoint.Y
                            );
                    }
                    else
                    {
                        difference = new Size(
                            e.Location.X - multiMoveLastLocation.Value.X,
                            e.Location.Y - multiMoveLastLocation.Value.Y
                            );
                    }
                    multiMoveLastLocation = e.Location;
                    int snapDistance = 2;
                    int minXDisctance = snapDistance;
                    int minYDisctance = snapDistance;
                    //snap to other places
                    foreach (ComputerPlace cp in ComputerPlace.Cache)
                    {
                        if (mouseDownComputerPlace != cp && inDistance(mouseDownComputerPlace.MapX + difference.Width, cp.MapX) < snapDistance)
                        {
                            minXDisctance = nearest(minXDisctance, difference.Width + calculateDistance(mouseDownComputerPlace.MapX + difference.Width, cp.MapX));
                        }
                        if (mouseDownComputerPlace != cp && inDistance(mouseDownComputerPlace.MapY + difference.Height, cp.MapY) < snapDistance)
                        {
                            minYDisctance = nearest(minYDisctance, difference.Height + calculateDistance(mouseDownComputerPlace.MapY + difference.Height, cp.MapY));
                        }
                    }
                    if (minXDisctance < snapDistance)
                        difference = new Size(difference.Width + minXDisctance, difference.Height);
                    if (minYDisctance < snapDistance)
                        difference = new Size(difference.Width, difference.Height + minYDisctance);

                    //moving all selected objects with the chosen difference
                    foreach (ListViewItem li in this.PlacesListView.SelectedItems)
                    {
                        ComputerPlace p = (ComputerPlace)li.Tag;
                        //p.Coord += difference;
                        p.MapX += difference.Width;
                        p.MapY += difference.Height;
                    }

                    if (this.PlacesListView.SelectedItems.Count == 1)
                    {
                        //single move
                        placeEditor.SelectedObject = mouseDownComputerPlace;
                        changed();
                    }
                    else if (this.PlacesListView.SelectedItems.Count > 1)
                    {

                        editObjects();
                    }

                    MapPictureBox.Refresh();
                }
                // if drag start from blank area then paint selection area
                else if (e.Button == MouseButtons.Left && mouseDownComputerPlace == null)
                {
                    //set multiselect range so we can draw the selectarea rectangle
                    multiSelectStart = mouseDownPoint;
                    multiSelectEnd = e.Location;

                    int Xleft, Xright, Yup, Ybottom;
                    if (mouseDownPoint.X > e.Location.X)
                    {
                        Xleft = e.Location.X;
                        Xright = mouseDownPoint.X;
                    }
                    else
                    {
                        Xleft = mouseDownPoint.X;
                        Xright = e.Location.X;
                    }

                    if (mouseDownPoint.Y > e.Location.Y)
                    {
                        Yup = e.Location.Y;
                        Ybottom = mouseDownPoint.Y;
                    }
                    else
                    {
                        Yup = mouseDownPoint.Y;
                        Ybottom = e.Location.Y;

                    }
                    multiSelectStart = new Point(Xleft, Yup);
                    multiSelectEnd = new Point(Xright, Ybottom);

                    //selecting items
                    disableEvents = true;
                    this.PlacesListView.BeginUpdate();
                    foreach (ListViewItem li in this.PlacesListView.Items)
                    {
                        ComputerPlace p = (ComputerPlace)li.Tag;
                        if (p.MapX + (p.Width - 1) >= multiSelectStart.Value.X &&
                            p.MapX <= multiSelectEnd.Value.X &&
                            p.MapY >= multiSelectStart.Value.Y &&
                            p.MapY <= multiSelectEnd.Value.Y)
                        {
                            if (!li.Selected)
                                li.Selected = true;
                        }
                        else if (li.Selected)
                        {
                            li.Selected = false;
                        }
                    }
                    if (this.PlacesListView.SelectedItems.Count == 0)
                    {
                        placeEditor.SelectedObject = null;
                    }
                    this.PlacesListView.EndUpdate();
                    this.MapPictureBox.Refresh();
                    disableEvents = false;
                }
            }
        }

        private void editObjects()
        {
            List<ComputerPlace> selectedplaces = new List<ComputerPlace>();
            foreach (ListViewItem lvi in this.PlacesListView.SelectedItems)
            {
                selectedplaces.Add((ComputerPlace)lvi.Tag);

            }
            placeEditor.SelectedObjects = selectedplaces.ToArray();
        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            save();
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void toolStripRefreshButton_Click(object sender, EventArgs e)
        {
            PlacesListView.Items.Clear();
            loadComputerPlaces();
            MapPictureBox.Refresh();
        }

        private void usersToolStripPrintButton_Click(object sender, EventArgs e)
        {
            UsersFinderForm frm = new UsersFinderForm();
            frm.ShowDialog(this);
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {

            ApiSettings frm = new ApiSettings();
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    User.LoadAll();
                    Map.LoadAll();
                    loadPlacemap();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Cannot communicate with Moya\r\n" + ex.Message);
                }
            }
        }

        private void MapsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            SelectedMap = (Map)MapsComboBox.SelectedItem;
            loadComputerPlaces();
            loadImage();
        }

        private void PlacesListView_DoubleClick(object sender, EventArgs e)
        {
            if (PlacesListView.SelectedItems.Count == 1)
            {
                UserInfoForm frm = new UserInfoForm();
                frm.User = ((ComputerPlace)PlacesListView.SelectedItems[0].Tag).User;
                frm.Show();
            }
        }

        private void cardLocationInputToolStripButton_Click(object sender, EventArgs e)
        {
            CardLocationInput frm = new CardLocationInput();
            frm.Show();
        }

        private void incomingFormToolStripButton_Click(object sender, EventArgs e)
        {
            IncomingForm frm = new IncomingForm();
            frm.Show();
        }
        private void showBuyerInfo(object sender, EventArgs e)
        {
            ShowCardInformation frm = new ShowCardInformation();
            frm.Show();

        }
        private void cardInfoToolStripButton_Click(object sender, EventArgs e)
        {
            ShowCardInformation frm = new ShowCardInformation();
            frm.Show();
        }

        private void searchTextBox_TextChanged(object sender, EventArgs e)
        {
            searchTimer.Stop();
            searchTimer.Start();
        }

        private void searchTimer_Tick(object sender, EventArgs e)
        {
            searchTimer.Stop();
            ListView.ListViewItemCollection items = PlacesListView.Items;
            PlacesListView.BeginUpdate();
            if (searchTextBox.Text.Length > 0)
            {
                foreach (ListViewItem lvi in items)
                {

                    ComputerPlace place = (ComputerPlace)lvi.Tag;
                    if (
                        place.Name == searchTextBox.Text
                        || place.User != null
                            && (
                                place.ReserverUserName.ToLower().Contains(searchTextBox.Text.ToLower())
                                || place.User.ToString().ToLower().Contains(searchTextBox.Text.ToLower())
                            )
                        )
                    {
                        lvi.Selected = true;
                    }
                    else
                        lvi.Selected = false;
                }
            }
            
            PlacesListView.EndUpdate();

        }

        private void ImageRefreshTimer_Tick(object sender, EventArgs e)
        {
            ImageRefreshTimer.Stop();
            this.MapPictureBox.Refresh();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {


        }


        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            
        }

        private void orgMealToolStripButton_Click(object sender, EventArgs e)
        {
            OrgMealCounter frm = new OrgMealCounter();
            frm.Show();

        }

        

    }
}