aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Technician/ViewModels/MachineTechViewVM.cs
blob: ab5d2ebb130c795173b3f859e4467a788829a73e (pla
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Scripting.IDE.Projects
{
    public abstract class CSharpProject : Project
    {

    }
}
'>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 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
using Google.Protobuf.Collections;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Tango.Core.Helpers;
using Tango.Editors;
using Tango.BL.Entities;
using Tango.Integration.Operation;
using Tango.MachineStudio.Common.Diagnostics;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.MachineStudio.Technician.Editors;
using Tango.MachineStudio.Technician.Project;
using Tango.MachineStudio.Technician.TechItems;
using Tango.PMR.Diagnostics;
using Tango.Settings;
using Tango.SharedUI;
using Tango.Integration.ExternalBridge;
using Tango.BL.Enumerations;
using Tango.BL;
using Tango.MachineStudio.Common.EventLogging;
using Tango.MachineStudio.Common;
using Tango.Core.Commands;
using Tango.MachineStudio.Technician.Helpers;
using Tango.MachineStudio.Technician.Models;
using Tango.Logging;
using Microsoft.WindowsAPICodePack.Dialogs;
using RealTimeGraphX;
using RealTimeGraphX.DataPoints;
using Tango.MachineStudio.Technician.Views;
using RealTimeGraphX.WPF;

namespace Tango.MachineStudio.Technician.ViewModels
{
    /// <summary>
    /// Represents the MachineTechView View Model.
    /// </summary>
    /// <seealso cref="Tango.SharedUI.ViewModel" />
    /// <seealso cref="Tango.MachineStudio.Common.StudioApplication.IShutdownListener" />
    public class MachineTechViewVM : StudioViewModel
    {
        private List<PropertyInfo> _diagnoticsMonitorsDataProperties;
        private IDiagnosticsFrameProvider _diagnosticsFrameProvider;
        private Dictionary<SingleGraphItem, TechGraphController> _singleControllers;
        private Dictionary<MultiGraphItem, TechGraphController> _multiControllers;
        private static object _elementsLock = new object();
        private String _lastTechProjectFile;
        private INotificationProvider _notification;
        private IEventLogger _eventLogger;
        private DateTime _lastDiagnosticsResponseUpdate;
        private const int MIN_DIAGNOSTICS_UPDATE_MILI = 500;
        private TechnicianModuleSettings _settings;

        private List<SingleTechRecordingData> _single_graphs_recordings;
        private List<MultiTechRecordingData> _multi_graph_recordings;
        private List<SingleTechRecordingData> _single_monitors_recordings;
        private List<MultiTechRecordingData> _multi_monitors_recordings;

        private DateTime _start_time = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
        private DateTime _last_time = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

        #region Properties

        private ObservableCollection<MachineTechTabVM> _tabs;
        /// <summary>
        /// Gets or sets the elements tabs.
        /// </summary>
        public ObservableCollection<MachineTechTabVM> Tabs
        {
            get { return _tabs; }
            set { _tabs = value; RaisePropertyChangedAuto(); }
        }

        private MachineTechTabVM _selectedTab;
        /// <summary>
        /// Gets or sets the selected tab.
        /// </summary>
        public MachineTechTabVM SelectedTab
        {
            get { return _selectedTab; }
            set
            {
                _selectedTab = value;
                RaisePropertyChangedAuto();

                foreach (var tab in Tabs.Where(x => x != _selectedTab))
                {
                    tab.IsSelected = false;
                }

                if (_selectedTab != null)
                {
                    _selectedTab.IsSelected = true;
                }
            }
        }

        private ObservableCollection<TechItem> _availableTechItems;
        /// <summary>
        /// Gets or sets the available tech items.
        /// </summary>
        public ObservableCollection<TechItem> AvailableTechItems
        {
            get { return _availableTechItems; }
            set { _availableTechItems = value; RaisePropertyChangedAuto(); }
        }

        private TechItem _selectedTechItem;
        /// <summary>
        /// Gets or sets the selected available tech item.
        /// </summary>
        public TechItem SelectedTechItem
        {
            get { return _selectedTechItem; }
            set { _selectedTechItem = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the db adapter.
        /// </summary>
        public ObservablesStaticCollections Adapter { get; set; }

        /// <summary>
        /// Gets or sets the application manager.
        /// </summary>
        public IStudioApplicationManager ApplicationManager { get; set; }

        private IMachineOperator _machineOperator;
        /// <summary>
        /// Gets or sets the machine operator.
        /// </summary>
        public IMachineOperator MachineOperator
        {
            get { return _machineOperator; }
            set { _machineOperator = value; RaisePropertyChangedAuto(); }
        }

        private bool _disableRendering;
        /// <summary>
        /// Gets or sets a value indicating whether [disable rendering].
        /// </summary>
        public bool DisableRendering
        {
            get { return _disableRendering; }
            set { _disableRendering = value; RaisePropertyChangedAuto(); OnDisableRenderingChanged(); }
        }

        private bool _hideMenu;
        /// <summary>
        /// Gets or sets a value indicating whether [hide menu].
        /// </summary>
        public bool HideMenu
        {
            get { return _hideMenu; }
            set { _hideMenu = value; RaisePropertyChangedAuto(); }
        }

        private StartDiagnosticsResponse _currentDiagnosticsResponse;
        /// <summary>
        /// Gets or sets the current diagnostics response.
        /// </summary>
        public StartDiagnosticsResponse CurrentDiagnosticsResponse
        {
            get { return _currentDiagnosticsResponse; }
            set { _currentDiagnosticsResponse = value; RaisePropertyChanged(nameof(CurrentDiagnosticsResponse)); }
        }

        private int _currentDiagnosticsResponseSize;
        /// <summary>
        /// Gets or sets the size of the current diagnostics response.
        /// </summary>
        /// <value>
        /// The size of the current diagnostics response.
        /// </value>
        public int CurrentDiagnosticsResponseSize
        {
            get { return _currentDiagnosticsResponseSize; }
            set { _currentDiagnosticsResponseSize = value; RaisePropertyChanged(nameof(CurrentDiagnosticsResponseSize)); }
        }

        private int _graphsDurationSeconds;
        /// <summary>
        /// Gets or sets the graphs duration seconds.
        /// </summary>
        public int GraphsDurationSeconds
        {
            get { return _graphsDurationSeconds; }
            set { _graphsDurationSeconds = value; RaisePropertyChangedAuto(); }
        }

        private int _tempGraphsDurationSeconds;
        /// <summary>
        /// Gets or sets the temporary graphs duration seconds.
        /// </summary>
        public int TempGraphsDurationSeconds
        {
            get { return _tempGraphsDurationSeconds; }
            set { _tempGraphsDurationSeconds = value; RaisePropertyChangedAuto(); }
        }



        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the save as project command.
        /// </summary>
        public RelayCommand SaveAsProjectCommand { get; set; }

        /// <summary>
        /// Gets or sets the save project command.
        /// </summary>
        public RelayCommand SaveProjectCommand { get; set; }

        /// <summary>
        /// Gets or sets the open project command.
        /// </summary>
        public RelayCommand OpenProjectCommand { get; set; }

        /// <summary>
        /// Gets or sets the synchronize hardware configuration command.
        /// </summary>
        public RelayCommand SyncHardwareConfigurationCommand { get; set; }

        /// <summary>
        /// Gets or sets the upload hardware configuration command.
        /// </summary>
        public RelayCommand UploadHardwareConfigurationCommand { get; set; }

        /// <summary>
        /// Gets or sets the reset hardware configuration command.
        /// </summary>
        public RelayCommand ResetHardwareConfigurationCommand { get; set; }

        /// <summary>
        /// Gets or sets the update graphs duration command.
        /// </summary>
        public RelayCommand UpdateGraphsDurationCommand { get; set; }

        /// <summary>
        /// Gets or sets the add tab command.
        /// </summary>
        public RelayCommand AddTabCommand { get; set; }

        /// <summary>
        /// Gets or sets the remove tab command.
        /// </summary>
        public RelayCommand<MachineTechTabVM> RemoveTabCommand { get; set; }

        /// <summary>
        /// Gets or sets the new project command.
        /// </summary>
        public RelayCommand NewProjectCommand { get; set; }

        /// <summary>
        /// Gets or sets the rename tab command.
        /// </summary>
        public RelayCommand RenameTabCommand { get; set; }

        /// <summary>
        /// Gets or sets the import project tabs command.
        /// </summary>
        /// <value>
        /// The import project tabs command.
        /// </value>
        public RelayCommand ImportProjectTabsCommand { get; set; }

        /// <summary>
        /// Gets or sets the upload partial hardware configuration command.
        /// </summary>
        public RelayCommand UploadPartialHardwareConfigurationCommand { get; set; }

        /// <summary>
        /// Gets or sets the reset command.
        /// </summary>
        public RelayCommand ResetGraphsCommand { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MachineTechViewVM"/> class.
        /// </summary>
        /// <param name="applicationManager">The application manager.</param>
        /// <param name="notificationProvider">The notification provider.</param>
        public MachineTechViewVM(IStudioApplicationManager applicationManager, INotificationProvider notificationProvider, IDiagnosticsFrameProvider diagnosticsFrameProvider, IEventLogger eventLogger)
        {
            Tabs = new ObservableCollection<MachineTechTabVM>();
            Tabs.Add(new MachineTechTabVM() { IsSelected = true, Name = "Untitled" });
            SelectedTab = Tabs.First();

            _settings = SettingsManager.Default.GetOrCreate<TechnicianModuleSettings>();

            _single_graphs_recordings = new List<SingleTechRecordingData>();
            _multi_graph_recordings = new List<MultiTechRecordingData>();

            _single_monitors_recordings = new List<SingleTechRecordingData>();
            _multi_monitors_recordings = new List<MultiTechRecordingData>();

            GraphsDurationSeconds = _settings.GraphsDuration;
            TempGraphsDurationSeconds = GraphsDurationSeconds;

            _notification = notificationProvider;
            _eventLogger = eventLogger;
            _singleControllers = new Dictionary<SingleGraphItem, TechGraphController>();
            _multiControllers = new Dictionary<MultiGraphItem, TechGraphController>();
            AvailableTechItems = TechItem.GetAvailableTechItems().ToObservableCollection();
            SelectedTechItem = AvailableTechItems.FirstOrDefault();
            _diagnoticsMonitorsDataProperties = typeof(DiagnosticsMonitors).GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
            ApplicationManager = applicationManager;
            ApplicationManager.ConnectedMachineChanged += ApplicationManager_ConnectedMachineChanged;

            Adapter = ObservablesStaticCollections.Instance;

            OpenProjectCommand = new RelayCommand(OpenProject);
            SaveAsProjectCommand = new RelayCommand(SaveAsProject);
            SaveProjectCommand = new RelayCommand(SaveProject);

            _lastTechProjectFile = _settings.LastTechProjectFile;

            if (File.Exists(_lastTechProjectFile))
            {
                try
                {
                    OpenProjectFile(_lastTechProjectFile);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error loading last project file.");
                }
            }

            _diagnosticsFrameProvider = diagnosticsFrameProvider;
            _diagnosticsFrameProvider.FrameReceived += DiagnosticsFrameProvider_FrameReceived;

            UploadHardwareConfigurationCommand = new RelayCommand(UploadHardwareConfiguration);
            SyncHardwareConfigurationCommand = new RelayCommand(SyncHardwareConfiguration);
            ResetHardwareConfigurationCommand = new RelayCommand(() => ResetHardwareConfiguration());
            UpdateGraphsDurationCommand = new RelayCommand(() =>
            {
                GraphsDurationSeconds = TempGraphsDurationSeconds;
                _settings.GraphsDuration = GraphsDurationSeconds;
                ClearAllGraphs();
            });

            AddTabCommand = new RelayCommand(() => AddNewTab());
            RemoveTabCommand = new RelayCommand<MachineTechTabVM>(RemoveTab);
            NewProjectCommand = new RelayCommand(CreateNewProject);
            RenameTabCommand = new RelayCommand(RenameTab);
            ImportProjectTabsCommand = new RelayCommand(ImportProjectTabs);
            UploadPartialHardwareConfigurationCommand = new RelayCommand(UploadPartialHardwareConfiguration);
            ResetGraphsCommand = new RelayCommand(ClearAllGraphs);
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Applications the manager connected machine changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="machine">The machine.</param>
        private void ApplicationManager_ConnectedMachineChanged(object sender, IExternalBridgeClient machine)
        {
            MachineOperator = machine;

            if (MachineOperator != null)
            {
                ResetHardwareConfiguration(false);
            }

            ClearAllGraphs();
        }

        /// <summary>
        /// Handles the diagnostics frame provider data.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="response">The response.</param>
        private void DiagnosticsFrameProvider_FrameReceived(object sender, StartDiagnosticsResponse response)
        {
            PopulateDiagnosticsData(response);
        }

        #endregion

        #region Populate Diagnostics Data

        /// <summary>
        /// Populates the diagnostics data to the proper elements.
        /// </summary>
        /// <param name="data">The data.</param>
        private void PopulateDiagnosticsData(StartDiagnosticsResponse data)
        {
            if (data.Monitors == null) return;

            TimeSpan delta_base = DateTime.Now - _start_time;
            TimeSpan delta = (DateTime.Now - _last_time);
            double delta_mili = delta.TotalMilliseconds;
            _last_time = DateTime.Now;

            if (DateTime.Now > _lastDiagnosticsResponseUpdate.AddMilliseconds(MIN_DIAGNOSTICS_UPDATE_MILI))
            {
                CurrentDiagnosticsResponse = data;
                _lastDiagnosticsResponseUpdate = DateTime.Now;
                CurrentDiagnosticsResponseSize = data.CalculateSize();
            }

            foreach (var sr in _single_monitors_recordings)
            {
                var techMonitor = (sr.Tag as TechMonitor);

                var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == techMonitor.Name);

                if (prop != null)
                {
                    var points = GetDataArray(techMonitor, prop.GetValue(data.Monitors));
                    sr.PushData(points, delta_base, delta);
                }
            }

            foreach (var mr in _multi_monitors_recordings)
            {
                var techMonitor = (mr.Tag as TechMonitor);

                var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == techMonitor.Name);

                if (prop != null)
                {
                    var points = GetDataMatrix(techMonitor, prop.GetValue(data.Monitors));
                    mr.PushData(points, delta_base, delta);
                }
            }

            lock (_elementsLock)
            {
                var elements = Tabs.SelectMany(x => x.Elements).ToList();

                foreach (var item in elements.Select(x => x.HostedElement as TechItem))
                {
                    if (item.GetType() == typeof(MonitorItem))
                    {
                        MonitorItem monitorItem = item as MonitorItem;

                        if (DateTime.Now > monitorItem.LastUpdateTime.AddMilliseconds(monitorItem.UpdateInterval))
                        {
                            var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == monitorItem.TechMonitor.Name);

                            if (prop != null)
                            {
                                monitorItem.Value = GetDataLastValue(monitorItem.TechMonitor, prop.GetValue(data.Monitors));
                            }
                        }
                    }
                    else if (item.GetType() == typeof(MeterItem))
                    {
                        MeterItem meterItem = item as MeterItem;

                        if (DateTime.Now > meterItem.LastUpdateTime.AddMilliseconds(meterItem.UpdateInterval))
                        {
                            var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == meterItem.TechMonitor.Name);

                            if (prop != null)
                            {
                                meterItem.Value = GetDataLastValue(meterItem.TechMonitor, prop.GetValue(data.Monitors));
                            }
                        }
                    }
                    else if (item.GetType() == typeof(SingleGraphItem))
                    {
                        SingleGraphItem graphItem = item as SingleGraphItem;

                        var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == graphItem.TechMonitor.Name);

                        if (prop != null)
                        {
                            TechGraphController controller = null;

                            if (_singleControllers.TryGetValue(graphItem, out controller))
                            {
                                var points = GetDataArray(graphItem.TechMonitor, prop.GetValue(data.Monitors));

                                List<TimeSpanDataPoint> times = new List<TimeSpanDataPoint>();
                                var dPoints = points.Select(x => new DoubleDataPoint(x)).ToList();

                                for (int i = 0; i < points.Count; i++)
                                {
                                    times.Add(delta_base.Add(TimeSpan.FromMilliseconds((delta_mili / points.Count) * i)));
                                }

                                controller.PushData(times, dPoints);

                                var _graph_recording = _single_graphs_recordings.SingleOrDefault(x => x.Tag == graphItem);
                                if (_graph_recording != null)
                                {
                                    _graph_recording.PushData(points, delta_base, delta);
                                }
                            }
                        }
                    }
                    else if (item.GetType() == typeof(MultiGraphItem))
                    {
                        MultiGraphItem graphItem = item as MultiGraphItem;

                        var prop = _diagnoticsMonitorsDataProperties.SingleOrDefault(x => x.Name == graphItem.TechMonitor.Name);

                        if (prop != null)
                        {
                            TechGraphController controller = null;

                            if (_multiControllers.TryGetValue(graphItem, out controller))
                            {
                                var points = GetDataMatrix(graphItem.TechMonitor, prop.GetValue(data.Monitors));

                                if (points.Count > 0)
                                {
                                    List<TimeSpanDataPoint> times = new List<TimeSpanDataPoint>();
                                    var dPoints = points.Select(x => new List<DoubleDataPoint>(x.Select(y => new DoubleDataPoint(y)))).ToList();

                                    for (int i = 0; i < points[0].Count; i++)
                                    {
                                        times.Add(delta_base.Add(TimeSpan.FromMilliseconds((delta_mili / points[0].Count) * i)));
                                    }

                                    List<List<TimeSpanDataPoint>> timesMat = new List<List<TimeSpanDataPoint>>();

                                    for (int i = 0; i < controller.DataSeriesCollection.Count; i++)
                                    {
                                        timesMat.Add(times);
                                    }

                                    controller.PushData(timesMat, dPoints);
                                }

                                var _graph_recording = _multi_graph_recordings.SingleOrDefault(x => x.Tag == graphItem);
                                if (_graph_recording != null)
                                {
                                    _graph_recording.PushData(points, delta_base, delta);
                                }
                            }
                        }
                    }
                    else if (item.GetType() == typeof(DigitalOutItem))
                    {
                        DigitalOutItem digitalOutItem = item as DigitalOutItem;

                        var digitalPin = data.DigitalInterfaceStates.SingleOrDefault(x => x.InterfaceIO == (InterfaceIOs)digitalOutItem.TechIo.Code);

                        if (digitalPin != null)
                        {
                            digitalOutItem.EffectiveValue = digitalPin.Value;
                        }
                    }
                    else if (item.GetType() == typeof(DigitalInItem))
                    {
                        DigitalInItem digitalInItem = item as DigitalInItem;

                        var digitalPin = data.DigitalInterfaceStates.SingleOrDefault(x => x.InterfaceIO == (InterfaceIOs)digitalInItem.TechIo.Code);

                        if (digitalPin != null)
                        {
                            digitalInItem.Value = digitalPin.Value;
                        }
                    }
                    else if (item.GetType() == typeof(HeaterItem))
                    {
                        HeaterItem heaterItem = item as HeaterItem;

                        var heaterState = data.HeatersStates.SingleOrDefault(x => x.HeaterType == (HeaterType)heaterItem.TechHeater.Code);

                        if (heaterState != null)
                        {
                            heaterItem.HeaterState = heaterState;
                        }
                    }
                    else if (item.GetType() == typeof(ValveItem))
                    {
                        ValveItem valveItem = item as ValveItem;

                        var valveState = data.ValvesStates.SingleOrDefault(x => x.ValveType == (ValveType)valveItem.TechValve.Code);

                        if (valveState != null)
                        {
                            valveItem.EffectiveState = valveState.State;
                        }
                    }
                    else if (item.GetType() == typeof(BlowerItem))
                    {
                        BlowerItem blowerItem = item as BlowerItem;

                        if (data.Monitors.BlowerVoltage.Count > 0)
                        {
                            blowerItem.EffectiveActive = data.Monitors.BlowerVoltage.Last() > 0;
                        }
                    }
                    else if (item.GetType() == typeof(ControllerItem))
                    {
                        ControllerItem controllerItem = item as ControllerItem;

                        if (DateTime.Now > controllerItem.LastUpdateTime.AddMilliseconds(controllerItem.UpdateInterval))
                        {
                            var componentState = data.ComponentsStates.SingleOrDefault(x => (int)x.Component == controllerItem.TechController.Code);

                            if (componentState != null)
                            {
                                controllerItem.EffectiveValue = componentState.Value;
                            }
                        }
                    }
                }
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Gets the last data point from a protobuf repeated field.
        /// </summary>
        /// <param name="monitor">The monitor.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private double GetDataLastValue(TechMonitor monitor, object value)
        {
            if (!monitor.MultiChannel)
            {
                RepeatedField<double> arr = value as RepeatedField<double>;
                return arr.LastOrDefault();
            }
            else
            {
                RepeatedField<DoubleArray> arr = value as RepeatedField<DoubleArray>;
                return arr.Last().Data.Last();
            }
        }

        /// <summary>
        /// Gets the data array from a protobuf repeated field.
        /// </summary>
        /// <param name="monitor">The monitor.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private List<double> GetDataArray(TechMonitor monitor, object value)
        {
            return (value as RepeatedField<double>).ToList();
        }

        /// <summary>
        /// Gets the data matrix from a protobuf repeated field of <see cref="DoubleArray"/>.
        /// </summary>
        /// <param name="monitor">The monitor.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private List<List<double>> GetDataMatrix(TechMonitor monitor, object value)
        {
            DoubleArray[] arrayOfDoubles = Enumerable.ToArray(value as IEnumerable<DoubleArray>);
            return arrayOfDoubles.Select(x => x.Data.ToList()).ToList();
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Called when the disable rendering has been changed
        /// </summary>
        protected virtual void OnDisableRenderingChanged()
        {
            //foreach (var controller in _singleControllers)
            //{
            //    controller.Value.ChangeRenderMode(!DisableRendering);
            //}

            //foreach (var controller in _multiControllers)
            //{
            //    controller.Value.ChangeRenderMode(!DisableRendering);
            //}
        }

        #endregion

        #region Add/Remove Element

        /// <summary>
        /// Creates a new tech element by the specified bounds and the current selected element.
        /// </summary>
        /// <param name="bounds">The bounds.</param>
        public void CreateElement(Rect bounds)
        {
            CreateElement(SelectedTechItem, bounds);
        }

        /// <summary>
        /// Creates a new tech element by the specified tech item instance and bounds.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="bounds">The bounds.</param>
        private void CreateElement(TechItem item, Rect bounds)
        {
            if (item is MonitorItem)
            {
                CreateElement<MonitorElementEditor, MonitorItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault());
            }
            else if (item is MeterItem)
            {
                CreateElement<MeterElementEditor, MeterItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault());
            }
            else if (item is HeaterItem)
            {
                var editor = CreateElement<HeaterElementEditor, HeaterItem, TechHeater>(bounds, Adapter.TechHeaters.FirstOrDefault());
                InitTechHeater(editor.HeaterItem);
            }
            else if (item is ValveItem)
            {
                var editor = CreateElement<ValveElementEditor, ValveItem, TechValve>(bounds, Adapter.TechValves.FirstOrDefault());
                InitTechValveItem(editor.ValveItem);
            }
            else if (item is SingleGraphItem)
            {
                var editor = CreateElement<SingleGraphElementEditor, SingleGraphItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault());
                InitSingleGraphitem(editor.GraphItem, editor);
            }
            else if (item is MultiGraphItem)
            {
                var editor = CreateElement<MultiGraphElementEditor, MultiGraphItem, TechMonitor>(bounds, Adapter.TechMonitors.Where(x => x.MultiChannel).FirstOrDefault());
                InitMultiGraphItem(editor.GraphItem, editor);
            }
            else if (item is MotorItem)
            {
                var editor = CreateElement<MotorElementEditor, MotorItem, HardwareMotorType>(bounds, Adapter.HardwareMotorTypes.FirstOrDefault());
                InitMotorItem(editor.MotorItem);
            }
            else if (item is DispenserItem)
            {
                var editor = CreateElement<DispenserElementEditor, DispenserItem, TechDispenser>(bounds, Adapter.TechDispensers.FirstOrDefault());
                InitDispenserItem(editor.DispenserItem);
            }
            else if (item is ThreadMotionItem)
            {
                var editor = CreateElement<ThreadMotionElementEditor, ThreadMotionItem, object>(bounds, null);
                InitThreadMotionItem(editor.ThreadMotionItem);
            }
            else if (item is MotorGroupItem)
            {
                var editor = CreateElement<MotorGroupElementEditor, MotorGroupItem, object>(bounds, null);
                InitMotorGroupItem(editor.MotorGroupItem);
            }
            else if (item is DigitalOutItem)
            {
                var editor = CreateElement<DigitalOutElementEditor, DigitalOutItem, TechIo>(bounds, Adapter.TechIos.Where(x => x.Type == IOType.DigitalOutput.ToInt32()).FirstOrDefault());
                InitDigitalOutItem(editor.DigitalOutItem);
            }
            else if (item is DigitalInItem)
            {
                CreateElement<DigitalInElementEditor, DigitalInItem, TechIo>(bounds, Adapter.TechIos.Where(x => x.Type == IOType.DigitalInput.ToInt32()).FirstOrDefault());
            }
            else if (item is ControllerItem)
            {
                var editor = CreateElement<ControllerElementEditor, ControllerItem, TechController>(bounds, Adapter.TechControllers.FirstOrDefault());
                InitControllerItem(editor.ControllerItem);
            }
            else if (item is PidItem)
            {
                CreateElement<PidElementEditor, PidItem, HardwarePidControlType>(bounds, Adapter.HardwarePidControlTypes.FirstOrDefault());
            }
            else if (item is WinderItem)
            {
                CreateElement<WinderElementEditor, WinderItem, HardwareWinderType>(bounds, Adapter.HardwareWinderTypes.FirstOrDefault());
            }
            else if (item is DancerItem)
            {
                CreateElement<DancerElementEditor, DancerItem, HardwareDancerType>(bounds, Adapter.HardwareDancerTypes.FirstOrDefault());
            }
            else if (item is SpeedSensorItem)
            {
                CreateElement<SpeedSensorElementEditor, SpeedSensorItem, HardwareSpeedSensorType>(bounds, Adapter.HardwareSpeedSensorTypes.FirstOrDefault());
            }
            else if (item is BlowerItem)
            {
                var editor = CreateElement<BlowerElementEditor, BlowerItem, HardwareBlowerType>(bounds, Adapter.HardwareBlowerTypes.FirstOrDefault());
                InitBlowerItem(editor.BlowerItem);
            }
            else if (item is BreakSensorItem)
            {
                CreateElement<BreakSensorElementEditor, BreakSensorItem, HardwareBreakSensorType>(bounds, Adapter.HardwareBreakSensorTypes.FirstOrDefault());
            }
            else if (item is ProcessParametersItem)
            {
                var editor = CreateElement<ProcessParametersElementEditor, ProcessParametersItem, object>(bounds, null);
                InitProcessParameterItem(editor.ProcessParametersItem);
            }
            else if (item is JobRunnerItem)
            {
                var editor = CreateElement<JobRunnerElementEditor, JobRunnerItem, object>(bounds, null);
                InitJobRunnerItem(editor.JobRunnerItem);
            }
            else if (item is TextItem)
            {
                CreateElement<TextElementEditor, TextItem, object>(bounds, null);
            }
            else if (item is MonitorRecorderItem)
            {
                var editor = CreateElement<MonitorRecorderElementEditor, MonitorRecorderItem, object>(bounds, null);
                InitMonitorRecorderItem(editor.MonitorRecorderItem);
            }
        }

        /// <summary>
        /// Creates a new element by the specified editor type, tech item type, bounds and tech item constructor value.
        /// </summary>
        /// <typeparam name="Editor">The type of the editor.</typeparam>
        /// <typeparam name="Tech">The type of the tech.</typeparam>
        /// <typeparam name="Value">The type of the value.</typeparam>
        /// <param name="bounds">The bounds.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        private Editor CreateElement<Editor, Tech, Value>(Rect bounds, Value value) where Editor : IElementEditor where Tech : TechItem
        {
            TechItem item = Activator.CreateInstance(typeof(Tech), new object[] { value }) as TechItem;
            IElementEditor editor = Activator.CreateInstance(typeof(Editor), new object[] { ((Tech)item), bounds }) as IElementEditor;
            SelectedTab.Elements.Add(editor);
            return (Editor)editor;
        }

        /// <summary>
        /// Creates a new element by the specified editor type and tech item instance.
        /// </summary>
        /// <typeparam name="Editor">The type of the editor.</typeparam>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        private Editor CreateElement<Editor>(TechItem item) where Editor : IElementEditor
        {
            IElementEditor editor = Activator.CreateInstance(typeof(Editor), new object[] { item, item.GetBounds() }) as IElementEditor;
            SelectedTab.Elements.Add(editor);
            return (Editor)editor;
        }

        /// <summary>
        /// Adds a new tech item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void AddTechItem(TechItem item)
        {
            if (item is MonitorItem)
            {
                (item as MonitorItem).TechMonitor = Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<MonitorElementEditor>(item);
            }
            else if (item is HeaterItem)
            {
                (item as HeaterItem).TechHeater = Adapter.TechHeaters.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<HeaterElementEditor>(item);
            }
            else if (item is ValveItem)
            {
                (item as ValveItem).TechValve = Adapter.TechValves.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<ValveElementEditor>(item);
            }
            else if (item is MeterItem)
            {
                (item as MeterItem).TechMonitor = Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<MeterElementEditor>(item);
            }
            else if (item is SingleGraphItem)
            {
                (item as SingleGraphItem).TechMonitor = Adapter.TechMonitors.Where(x => !x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<SingleGraphElementEditor>(item);
                InitSingleGraphitem(editor.GraphItem, editor);
            }
            else if (item is MultiGraphItem)
            {
                (item as MultiGraphItem).TechMonitor = Adapter.TechMonitors.Where(x => x.MultiChannel).FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<MultiGraphElementEditor>(item);
                InitMultiGraphItem(editor.GraphItem, editor);
            }
            else if (item is MotorItem)
            {
                (item as MotorItem).HardwareMotorType = Adapter.HardwareMotorTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<MotorElementEditor>(item);
                InitMotorItem(editor.MotorItem);
            }
            else if (item is DispenserItem)
            {
                (item as DispenserItem).TechDispenser = Adapter.TechDispensers.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<DispenserElementEditor>(item);
                InitDispenserItem(editor.DispenserItem);
            }
            else if (item is ThreadMotionItem)
            {
                var editor = CreateElement<ThreadMotionElementEditor>(item);
                InitThreadMotionItem(editor.ThreadMotionItem);
            }
            else if (item is MotorGroupItem)
            {
                var editor = CreateElement<MotorGroupElementEditor>(item);
                InitMotorGroupItem(editor.MotorGroupItem);
            }
            else if (item is DigitalOutItem)
            {
                (item as DigitalOutItem).TechIo = Adapter.TechIos.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<DigitalOutElementEditor>(item);
                InitDigitalOutItem(editor.DigitalOutItem);
            }
            else if (item is DigitalInItem)
            {
                (item as DigitalInItem).TechIo = Adapter.TechIos.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<DigitalInElementEditor>(item);
            }
            else if (item is ControllerItem)
            {
                (item as ControllerItem).TechController = Adapter.TechControllers.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<ControllerElementEditor>(item);
                InitControllerItem(editor.ControllerItem);
            }
            else if (item is PidItem)
            {
                (item as PidItem).HardwarePidType = Adapter.HardwarePidControlTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<PidElementEditor>(item);
            }
            else if (item is WinderItem)
            {
                (item as WinderItem).HardwareWinderType = Adapter.HardwareWinderTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<WinderElementEditor>(item);
            }
            else if (item is DancerItem)
            {
                (item as DancerItem).HardwareDancerType = Adapter.HardwareDancerTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<DancerElementEditor>(item);
            }
            else if (item is SpeedSensorItem)
            {
                (item as SpeedSensorItem).HardwareSpeedSensorType = Adapter.HardwareSpeedSensorTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<SpeedSensorElementEditor>(item);
            }
            else if (item is BlowerItem)
            {
                (item as BlowerItem).HardwareBlowerType = Adapter.HardwareBlowerTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                var editor = CreateElement<BlowerElementEditor>(item);
                InitBlowerItem(editor.BlowerItem);
            }
            else if (item is BreakSensorItem)
            {
                (item as BreakSensorItem).HardwareBreakSensorType = Adapter.HardwareBreakSensorTypes.FirstOrDefault(x => x.Guid == item.ItemGuid);
                CreateElement<BreakSensorElementEditor>(item);
            }
            else if (item is ProcessParametersItem)
            {
                var editor = CreateElement<ProcessParametersElementEditor>(item);
                InitProcessParameterItem(editor.ProcessParametersItem);
            }
            else if (item is JobRunnerItem)
            {
                var editor = CreateElement<JobRunnerElementEditor>(item);
                InitJobRunnerItem(editor.JobRunnerItem);
            }
            else if (item is TextItem)
            {
                CreateElement<TextElementEditor>(item);
            }
            else if (item is MonitorRecorderItem)
            {
                var editor = CreateElement<MonitorRecorderElementEditor>(item);
                InitMonitorRecorderItem(editor.MonitorRecorderItem);
            }
        }

        /// <summary>
        /// Called when elements have been removed
        /// </summary>
        /// <param name="elements">The elements.</param>
        public void OnElementsRemoved(List<IElementEditor> elements)
        {
            foreach (var element in elements)
            {
                if (element.HostedElement is SingleGraphItem)
                {
                    var _graph_recording = _single_graphs_recordings.SingleOrDefault(x => x.Tag == element.HostedElement);

                    if (_graph_recording != null)
                    {
                        (_graph_recording.Tag as SingleGraphItem).StopRecording();
                        _single_graphs_recordings.Remove(_graph_recording);
                        _graph_recording.Dispose();
                    }
                }
                else if (element.HostedElement is MultiGraphItem)
                {
                    var _graph_recording = _multi_graph_recordings.SingleOrDefault(x => x.Tag == element.HostedElement);

                    if (_graph_recording != null)
                    {
                        (_graph_recording.Tag as MultiGraphItem).StopRecording();
                        _multi_graph_recordings.Remove(_graph_recording);
                        _graph_recording.Dispose();
                    }
                }
            }
        }

        /// <summary>
        /// Called when elements have been pasted
        /// </summary>
        /// <param name="elements">The elements.</param>
        public void OnElementsPasted(List<IElementEditor> elements)
        {
            foreach (var element in elements)
            {
                if (element is SingleGraphElementEditor)
                {
                    var graphItem = element.HostedElement as SingleGraphItem;
                    var editor = element as SingleGraphElementEditor;

                    TechGraphController controller = new TechGraphController();
                    controller.DataSeriesCollection.Add(new WpfGraphDataSeries()
                    {
                        Stroke = Colors.DodgerBlue,
                    });
                    editor.InnerGraph.Controller = controller;

                    graphItem.Editor = editor;

                    _singleControllers.Add(graphItem, controller);
                }
                else if (element is MultiGraphElementEditor)
                {
                    var graphItem = element.HostedElement as MultiGraphItem;
                    var editor = element as MultiGraphElementEditor;

                    TechGraphController controller = new TechGraphController(500);

                    for (int i = 0; i < graphItem.TechMonitor.ChannelCount; i++)
                    {
                        controller.DataSeriesCollection.Add(new WpfGraphDataSeries()
                        {
                            Stroke = ColorHelper.GetRandomColor(),
                            Name = graphItem.TechMonitor.Name.First() + (i + 1).ToString(),
                        });
                    }

                    editor.InnerGraph.Controller = controller;

                    graphItem.Editor = editor;

                    _multiControllers.Add(graphItem, controller);
                }
                else if (element is MotorElementEditor)
                {
                    var motorItem = element.HostedElement as MotorItem;
                    InitMotorItem(motorItem);
                }
                else if (element is DispenserElementEditor)
                {
                    var dispenser = element.HostedElement as DispenserItem;
                    InitDispenserItem(dispenser);
                }
                else if (element is DigitalOutElementEditor)
                {
                    var ioItem = element.HostedElement as DigitalOutItem;
                    InitDigitalOutItem(ioItem);
                }
                else if (element is ThreadMotionElementEditor)
                {
                    var threadMotionItem = element.HostedElement as ThreadMotionItem;
                    InitThreadMotionItem(threadMotionItem);
                }
                else if (element is MotorGroupElementEditor)
                {
                    var motorGroupItem = element.HostedElement as MotorGroupItem;
                    InitMotorGroupItem(motorGroupItem);
                }
                else if (element is ControllerElementEditor)
                {
                    var controllerItem = element.HostedElement as ControllerItem;
                    InitControllerItem(controllerItem);
                }
                else if (element is MonitorRecorderElementEditor)
                {
                    var item = element.HostedElement as MonitorRecorderItem;
                    InitMonitorRecorderItem(item);
                }
                else if (element is ValveElementEditor)
                {
                    var item = element.HostedElement as ValveItem;
                    InitTechValveItem(item);
                }
                else if (element is BlowerElementEditor)
                {
                    var item = element.HostedElement as BlowerItem;
                    InitBlowerItem(item);
                }
                else if (element is HeaterElementEditor)
                {
                    var item = element.HostedElement as HeaterItem;
                    InitTechHeater(item);
                }
                else if (element is ProcessParametersElementEditor)
                {
                    var item = element.HostedElement as ProcessParametersItem;
                    InitProcessParameterItem(item);
                }
            }
        }

        #endregion

        #region Init Tech Items

        /// <summary>
        /// Initializes the monitor recorder item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitMonitorRecorderItem(MonitorRecorderItem item)
        {
            item.RecordingStarted += () =>
            {
                CommonOpenFileDialog dlg = new CommonOpenFileDialog();
                dlg.Title = "Select a folder to place all CSV files.";
                dlg.IsFolderPicker = true;
                if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    foreach (var monitor in item.GetSelectedMonitors())
                    {
                        if (!monitor.MultiChannel)
                        {
                            _single_monitors_recordings.Add(new SingleTechRecordingData(monitor.Description, dlg.FileName + "\\" + monitor.Description + ".csv") { Tag = monitor });
                        }
                        else
                        {
                            _multi_monitors_recordings.Add(new MultiTechRecordingData(monitor.Description, monitor.ChannelCount, dlg.FileName + "\\" + monitor.Description + ".csv") { Tag = monitor });
                        }
                        item.StartRecording();
                    }
                }
            };

            item.RecordingStopped += () =>
            {
                item.StopRecording();

                foreach (var sr in _single_monitors_recordings)
                {
                    sr.Dispose();
                }

                _single_monitors_recordings.Clear();

                foreach (var mr in _multi_monitors_recordings)
                {
                    mr.Dispose();
                }

                _multi_monitors_recordings.Clear();
            };
        }

        /// <summary>
        /// Initializes the tech valve.
        /// </summary>
        /// <param name="item">The valve item.</param>
        private void InitTechValveItem(ValveItem item)
        {
            item.StateChanged += async (x, state) =>
            {
                try
                {
                    CheckMachineOperator();
                    await MachineOperator.SetValveState((ValveType)item.TechValve.Code, state);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician set valve state command on '{0}'.", item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician set valve state command on '{0}'.", item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the blower item.
        /// </summary>
        /// <param name="item">The blower item.</param>
        private void InitBlowerItem(BlowerItem item)
        {
            item.SetCommandClicked += async (_, isActive) =>
            {
                try
                {
                    CheckMachineOperator();
                    await MachineOperator.SetBlowerState((PMR.Hardware.HardwareBlowerType)item.HardwareBlower.HardwareBlowerType.Code, isActive, item.HardwareBlower.Voltage);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, $"Error executing SetBlowerState command for blower {item.HardwareBlower.HardwareBlowerType.Name}.");
                    _eventLogger.Log(ex, $"Error executing SetBlowerState command for blower {item.HardwareBlower.HardwareBlowerType.Name}.");
                }
            };
        }

        /// <summary>
        /// Initializes the tech heater.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitTechHeater(HeaterItem item)
        {
            item.SetCommandClicked += async () =>
            {
                try
                {
                    CheckMachineOperator();
                    await MachineOperator.SetHeaterState((HeaterType)item.TechHeater.Code, item.SetPoint);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, $"Error executing SetHeaterState command for heater {item.TechHeater.Name}.");
                    _eventLogger.Log(ex, $"Error executing SetHeaterState command for heater {item.TechHeater.Name}.");
                }
            };
        }

        /// <summary>
        /// Initializes the motor item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitMotorItem(MotorItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)item.HardwareMotorType.Code,
                            Speed = item.Speed,
                            Direction = MotorDirection.Forward,
                        });
                    }
                    else if (action == MotorActionType.ForwardReleased)
                    {
                        await MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)item.HardwareMotorType.Code,
                        });
                    }
                    else if (action == MotorActionType.BackwardPressed)
                    {
                        await MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)item.HardwareMotorType.Code,
                            Speed = item.Speed,
                            Direction = MotorDirection.Backward,
                        });
                    }
                    else if (action == MotorActionType.BackwardReleased)
                    {
                        await MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)item.HardwareMotorType.Code,
                        });
                    }
                    else if (action == MotorActionType.HomingForwardStarted || action == MotorActionType.HomingBackwardStarted)
                    {
                        item.HomingProgress = 0;
                        item.IsHoming = true;
                        item.IsHomingCompleted = false;

                        MachineOperator.StartMotorHoming(new MotorHomingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)item.HardwareMotorType.Code,
                            Speed = item.Speed,
                            Direction = action == MotorActionType.HomingBackwardStarted ? MotorDirection.Backward : MotorDirection.Forward
                        })
                        .Subscribe((response) =>
                        {
                            item.HomingMaximumProgress = response.MaxProgress;
                            item.HomingProgress = response.Progress;

                        }, (ex) =>
                         {

                             item.IsHoming = false;
                             item.IsHomingCompleted = true;

                         }, () =>
                         {

                             item.IsHoming = false;
                             item.IsHomingCompleted = true;

                         });
                    }
                    else if (action == MotorActionType.HomingStopped)
                    {
                        await MachineOperator.StopMotorHoming(new MotorAbortHomingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)item.HardwareMotorType.Code,
                        });

                        item.IsHoming = false;
                    }
                }
                catch (Exception ex)
                {
                    item.IsHomingCompleted = true;
                    item.IsHoming = false;
                    item.HomingProgress = 0;
                    item.HomingMaximumProgress = 0;
                    LogManager.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the dispenser item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitDispenserItem(DispenserItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await MachineOperator.StartDispenserJogging(new DispenserJoggingRequest()
                        {
                            Index = item.TechDispenser.Code,
                            Direction = MotorDirection.Forward,
                            Speed = item.Speed,
                        });
                    }
                    else if (action == MotorActionType.ForwardReleased)
                    {
                        await MachineOperator.StopDispenserJogging(new DispenserAbortJoggingRequest()
                        {
                            Index = item.TechDispenser.Code,
                        });
                    }
                    else if (action == MotorActionType.BackwardPressed)
                    {
                        await MachineOperator.StartDispenserJogging(new DispenserJoggingRequest()
                        {
                            Index = item.TechDispenser.Code,
                            Direction = MotorDirection.Backward,
                            Speed = item.Speed,
                        });
                    }
                    else if (action == MotorActionType.BackwardReleased)
                    {
                        await MachineOperator.StopDispenserJogging(new DispenserAbortJoggingRequest()
                        {
                            Index = item.TechDispenser.Code,
                        });
                    }
                    else if (action == MotorActionType.HomingForwardStarted || action == MotorActionType.HomingBackwardStarted)
                    {
                        item.HomingProgress = 0;
                        item.IsHoming = true;
                        item.IsHomingCompleted = false;

                        MachineOperator.StartDispenserHoming(new DispenserHomingRequest()
                        {
                            Index = item.TechDispenser.Code,
                            Speed = item.Speed,
                            Direction = action == MotorActionType.HomingBackwardStarted ? MotorDirection.Backward : MotorDirection.Forward
                        })
                        .Subscribe((response) =>
                        {

                            item.HomingMaximumProgress = response.MaxProgress;
                            item.HomingProgress = response.Progress;

                        }, (ex) =>
                        {

                            item.IsHoming = false;
                            item.IsHomingCompleted = true;

                        }, () =>
                        {

                            item.IsHoming = false;
                            item.IsHomingCompleted = true;

                        });
                    }
                    else if (action == MotorActionType.HomingStopped)
                    {
                        await MachineOperator.StopDispenserHoming(new DispenserAbortHomingRequest()
                        {
                            Index = item.TechDispenser.Code,
                        });

                        item.IsHoming = false;
                    }
                }
                catch (Exception ex)
                {
                    item.IsHomingCompleted = true;
                    item.IsHoming = false;
                    item.HomingProgress = 0;
                    item.HomingMaximumProgress = 0;
                    LogManager.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the single graph item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="editor">The editor.</param>
        private void InitSingleGraphitem(SingleGraphItem item, SingleGraphElementEditor editor)
        {
            TechGraphController controller = new TechGraphController();
            controller.Range.AutoY = true;
            controller.Range.MinimumY = item.TechMonitor.Min;
            controller.Range.MaximumY = item.TechMonitor.Max;
            controller.Range.MaximumX = TimeSpan.FromSeconds(10);

            controller.DataSeriesCollection.Add(new WpfGraphDataSeries()
            {
                Stroke = Colors.DodgerBlue,
            });

            editor.InnerGraph.Controller = controller;

            item.Editor = editor;

            _singleControllers.Add(item, controller);

            item.RecordingStarted += () =>
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Title = "Save graph data as csv file";
                dlg.Filter = "CSV Files|*.csv";
                dlg.DefaultExt = ".csv";
                dlg.FileName = item.TechName;
                if (dlg.ShowDialog().Value)
                {
                    _single_graphs_recordings.Add(new SingleTechRecordingData(item.TechName, dlg.FileName) { Tag = item });
                    item.StartRecording();
                }
            };

            item.RecordingStopped += () =>
            {
                try
                {
                    item.StopRecording();

                    var graph_recording = _single_graphs_recordings.SingleOrDefault(x => x.Tag == item);

                    if (graph_recording != null)
                    {
                        _single_graphs_recordings.Remove(graph_recording);
                        graph_recording.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    _notification.ShowError(LogManager.Log(ex).Message);
                }
            };
        }

        /// <summary>
        /// Initializes the multi graph item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="editor">The editor.</param>
        private void InitMultiGraphItem(MultiGraphItem item, MultiGraphElementEditor editor)
        {
            TechGraphController controller = new TechGraphController(500);
            controller.Range.AutoY = true;
            controller.Range.MinimumY = item.TechMonitor.Min;
            controller.Range.MaximumY = item.TechMonitor.Max;
            controller.Range.MaximumX = TimeSpan.FromSeconds(10);

            for (int i = 0; i < item.TechMonitor.ChannelCount; i++)
            {
                controller.DataSeriesCollection.Add(new WpfGraphDataSeries()
                {
                    Stroke = ColorHelper.GetRandomColor(),
                    Name = item.TechMonitor.Name.First() + (i + 1).ToString(),
                });
            }

            editor.InnerGraph.Controller = controller;

            item.Editor = editor;

            _multiControllers.Add(item, controller);

            item.RecordingStarted += () =>
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Title = "Save graph data as csv file";
                dlg.Filter = "CSV Files|*.csv";
                dlg.DefaultExt = ".csv";
                dlg.FileName = item.TechName;
                if (dlg.ShowDialog().Value)
                {
                    _multi_graph_recordings.Add(new MultiTechRecordingData(item.TechName, item.TechMonitor.ChannelCount, dlg.FileName) { Tag = item });
                    item.StartRecording();
                }
            };

            item.RecordingStopped += () =>
            {
                try
                {
                    item.StopRecording();

                    var graph_recording = _multi_graph_recordings.SingleOrDefault(x => x.Tag == item);

                    if (graph_recording != null)
                    {
                        _multi_graph_recordings.Remove(graph_recording);
                        graph_recording.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    _notification.ShowError(LogManager.Log(ex).Message);
                }
            };
        }

        /// <summary>
        /// Initializes the thread motion item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitThreadMotionItem(ThreadMotionItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await MachineOperator.StartThreadJogging(new ThreadJoggingRequest()
                        {
                            Speed = item.Speed,
                        });
                    }
                    else if (action == MotorActionType.ForwardReleased || action == MotorActionType.BackwardReleased)
                    {
                        await MachineOperator.StopThreadJogging(new ThreadAbortJoggingRequest());
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format(String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName)));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the motor group item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitMotorGroupItem(MotorGroupItem item)
        {
            item.ActionExecuted += async (x, action) =>
            {
                try
                {
                    CheckMachineOperator();

                    if (action == MotorActionType.ForwardPressed)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)motor.Code,
                            Direction = MotorDirection.Forward,
                        })));
                    }
                    else if (action == MotorActionType.ForwardReleased)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)motor.Code,
                        })));
                    }
                    else if (action == MotorActionType.BackwardPressed)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StartMotorJogging(new MotorJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)motor.Code,
                            Direction = MotorDirection.Backward,
                        })));
                    }
                    else if (action == MotorActionType.BackwardReleased)
                    {
                        await Task.WhenAll(item.TechMotors.Select(motor => MachineOperator.StopMotorJogging(new MotorAbortJoggingRequest()
                        {
                            MotorType = (PMR.Hardware.HardwareMotorType)motor.Code,
                        })));
                    }
                    //else if (action == MotorActionType.HomingStarted)
                    //{
                    //    item.HomingProgress = 0;
                    //    item.IsHoming = true;
                    //    item.IsHomingCompleted = false;

                    //    MachineOperator.StartMotorHoming(new MotorHomingRequest()
                    //    {
                    //        Code = item.TechMotor.Code
                    //    })
                    //    .Subscribe((response) =>
                    //    {

                    //        item.HomingMaximumProgress = response.Message.MaxProgress;
                    //        item.HomingProgress = response.Message.Progress;

                    //    }, () =>
                    //    {

                    //        item.IsHoming = false;
                    //        item.IsHomingCompleted = true;

                    //    });
                    //}
                    //else if (action == MotorActionType.HomingStopped)
                    //{
                    //    await MachineOperator.StopMotorHoming(new MotorAbortHomingRequest()
                    //    {
                    //        Code = item.TechMotor.Code,
                    //    });

                    //    item.IsHoming = false;
                    //}
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician command '{0}' on item '{1}'.", action, item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the digital out item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitDigitalOutItem(DigitalOutItem item)
        {
            item.ValueChanged += async (x, value) =>
            {
                try
                {
                    CheckMachineOperator();
                    await MachineOperator.SetDigitalOut(new SetDigitalOutRequest() { InterfaceIO = (InterfaceIOs)item.TechIo.Code, Value = value });
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician set digital out command on '{0}'.", item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician set digital out command on '{0}'.", item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the controller item.
        /// </summary>
        /// <param name="item">The controller item.</param>
        private void InitControllerItem(ControllerItem item)
        {
            item.SetCommandClicked += async (_, __) =>
            {
                try
                {
                    CheckMachineOperator();
                    await MachineOperator.SetComponentValue(new SetComponentValueRequest()
                    {
                        Component = (ValueComponent)item.TechController.Code,
                        Value = item.Value
                    });
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, String.Format("Error executing technician set value component command on '{0}'.", item.TechName));
                    _eventLogger.Log(ex, String.Format("Error executing technician set value component command on '{0}'.", item.TechName));
                }
            };
        }

        /// <summary>
        /// Initializes the process parameter item.
        /// </summary>
        /// <param name="item">The item.</param>
        private void InitProcessParameterItem(ProcessParametersItem item)
        {
            item.PushParametersPressed += async (x, parameters) =>
            {
                try
                {
                    CheckMachineOperator();

                    using (_notification.PushTaskItem("Uploading process parameters..."))
                    {
                        try
                        {
                            await MachineOperator.UploadProcessParameters(parameters);
                        }
                        catch (Exception ex)
                        {
                            String msg = "Error uploading process parameters:" + Environment.NewLine + parameters.ToJsonString();
                            _eventLogger.Log(ex, msg);
                            LogManager.Log(ex, msg);
                            _notification.ShowError("Could not upload process parameters." + Environment.NewLine + ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _notification.ShowError(ex.Message);
                }
            };
        }

        /// <summary>
        /// Initializes the job runner item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <exception cref="NotImplementedException"></exception>
        private void InitJobRunnerItem(JobRunnerItem item)
        {
            item.StartJob += async () =>
            {
                try
                {
                    CheckMachineOperator();

                    var handler = await MachineOperator.Print(item.Job, item.ProcessParameters);

                    item.JobHandler = handler;

                    handler.StatusChanged += (x, status) =>
                    {
                        item.RunningJobStatus = status;
                    };

                    handler.Stopped += (x, e) =>
                    {
                        item.IsJobStarted = false;
                    };
                }
                catch (Exception ex)
                {
                    item.IsJobStarted = false;
                    _notification.ShowError(ex.Message);
                }
            };

            item.StopJob += () =>
            {
                if (item.JobHandler != null)
                {
                    item.JobHandler.Cancel();
                    item.JobHandler = null;
                }
            };
        }

        /// <summary>
        /// Checks the machine operator.
        /// </summary>
        /// <exception cref="InvalidOperationException">No machine connected.</exception>
        private void CheckMachineOperator()
        {
            if (MachineOperator == null || MachineOperator.State != Transport.TransportComponentState.Connected)
            {
                throw new InvalidOperationException("No machine connected.");
            }
        }

        #endregion

        #region Project Management

        /// <summary>
        /// Opens a file open dialog to select a project file.
        /// </summary>
        public void OpenProject()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Select Technician Project File";
            dlg.Filter = "Technician Project File|*.tpf";

            if (dlg.ShowDialog().Value)
            {
                OpenProjectFile(dlg.FileName);
            }
        }

        /// <summary>
        /// Opens the specified project file path.
        /// </summary>
        /// <param name="fileName">File path.</param>
        public MachineTechViewProject OpenProjectFile(String fileName, bool load = true)
        {
            MachineTechViewProject project = null;

            try
            {
                project = MachineTechViewProject.Load(fileName);

                if (project.Tabs.Count == 0)
                {
                    LogManager.Log($"Error loading project file {fileName}. Trying to load using legacy project loader.", LogCategory.Warning);

                    MachineTechViewProjectTab tab = new MachineTechViewProjectTab();
                    tab.Name = "Untitled";
                    tab.Items.AddRange(project.Items);
                    project.Items.Clear();
                    project.Tabs.Add(tab);
                }

                if (load)
                {
                    LoadProject(project);
                    _lastTechProjectFile = fileName;
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error loading project file {fileName}.");
                _notification.ShowError("An error occurred while trying to load the tech board project file.");
            }

            return project;
        }

        /// <summary>
        /// Loads the specified project.
        /// </summary>
        /// <param name="project">The project.</param>
        public void LoadProject(MachineTechViewProject project, bool appendToCurrentProject = false)
        {
            using (_notification.PushTaskItem("Loading technician project file..."))
            {
                if (!appendToCurrentProject)
                {
                    Tabs.Clear();
                    _singleControllers.Clear();
                    _multiControllers.Clear();
                }

                foreach (var tab in project.Tabs)
                {
                    MachineTechTabVM t = new MachineTechTabVM();
                    t.Name = tab.Name;
                    Tabs.Add(t);

                    SelectedTab = t;

                    foreach (var item in tab.Items)
                    {
                        if (item is MotorGroupItem)
                        {
                            (item as MotorGroupItem).TechMotors = ObservablesStaticCollections.Instance.HardwareMotorTypes.Where(x => (item as MotorGroupItem).ItemsGuids.Contains(x.Guid)).ToObservableCollection();
                        }
                        else if (item is MonitorRecorderItem)
                        {
                            (item as MonitorRecorderItem).SetSelectedMonitors(ObservablesStaticCollections.Instance.TechMonitors.Where(x => (item as MonitorRecorderItem).SelectedMonitorsGuids.Contains(x.Guid)).ToList());
                        }

                        AddTechItem(item);
                    }
                }

                SelectedTab = Tabs.ElementAt(project.SelectedTabIndex);
            }
        }

        /// <summary>
        /// Opens the file save dialog for selecting a project file target.
        /// </summary>
        private void SaveAsProject()
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "Select Technician Project Location";
            dlg.Filter = "Technician Project File|*.tpf";

            if (dlg.ShowDialog().Value)
            {
                SaveProjectFile(dlg.FileName);
            }
        }

        /// <summary>
        /// Saves the current project to the specified file path.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        private void SaveProjectFile(String fileName)
        {
            using (_notification.PushTaskItem("Saving technician project file..."))
            {
                MachineTechViewProject project = GenerateProjectFile();
                project.Save(fileName);
                _lastTechProjectFile = fileName;
            }
        }

        /// <summary>
        /// Saves the current opened project file. If not project file is opened will call <see cref="SaveAsProject"/>.
        /// </summary>
        private void SaveProject()
        {
            if (File.Exists(_lastTechProjectFile))
            {
                SaveProjectFile(_lastTechProjectFile);
            }
            else
            {
                SaveAsProject();
            }
        }

        /// <summary>
        /// Generates a project file from the current element setup.
        /// </summary>
        /// <returns></returns>
        private MachineTechViewProject GenerateProjectFile()
        {
            MachineTechViewProject project = new MachineTechViewProject();
            project.SelectedTabIndex = Tabs.IndexOf(SelectedTab);

            foreach (var tab in Tabs)
            {
                MachineTechViewProjectTab pTab = new MachineTechViewProjectTab();
                pTab.Name = tab.Name;

                foreach (var element in tab.Elements)
                {
                    if (element.HostedElement is MotorGroupItem)
                    {
                        var group = element.HostedElement as MotorGroupItem;
                        group.ItemsGuids = group.TechMotors.Select(x => x.Guid).ToList();
                    }

                    (element.HostedElement as TechItem).SetBounds(element.GetBounds());
                    pTab.Items.Add(element.HostedElement as TechItem);
                }

                project.Tabs.Add(pTab);
            }

            return project;
        }

        /// <summary>
        /// Removes the specified tab.
        /// </summary>
        /// <param name="tab">The tab.</param>
        private void RemoveTab(MachineTechTabVM tab)
        {
            if (_notification.ShowQuestion("Are you sure you want to delete the selected tab?"))
            {
                Tabs.Remove(tab);
                SelectedTab = Tabs.LastOrDefault();

                if (SelectedTab == null)
                {
                    AddNewTab("Untitled");
                }
            }
        }

        /// <summary>
        /// Adds a new tab.
        /// </summary>
        private bool AddNewTab(String name = null)
        {
            if (Tabs.Count > 7)
            {
                _notification.ShowError("Cannot exceed the maximum number of 8 tabs. You can remove a tab, or create a new project.");
                return false;
            }

            if (name == null)
            {
                name = _notification.ShowTextInput("Enter tab name", "Tab Name", "Untitled");
            }

            if (!String.IsNullOrWhiteSpace(name))
            {
                MachineTechTabVM t = new MachineTechTabVM();
                t.Name = name;
                Tabs.Add(t);
                SelectedTab = t;
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Creates a new project.
        /// </summary>
        private void CreateNewProject()
        {
            var to_remove = Tabs.ToList();

            if (AddNewTab())
            {
                _singleControllers.Clear();
                _multiControllers.Clear();

                foreach (var tab in to_remove)
                {
                    Tabs.Remove(tab);
                }
            }
        }

        /// <summary>
        /// Renames the tab.
        /// </summary>
        /// <param name="tab">The tab.</param>
        private void RenameTab()
        {
            if (SelectedTab != null)
            {
                var name = _notification.ShowTextInput("Enter tab name", "Tab Name", SelectedTab.Name);

                if (!String.IsNullOrWhiteSpace(name))
                {
                    SelectedTab.Name = name;
                }
            }
        }

        /// <summary>
        /// Imports a project file tabs to the current project.
        /// </summary>
        private void ImportProjectTabs()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Select Technician Project File";
            dlg.Filter = "Technician Project File|*.tpf";

            if (dlg.ShowDialog().Value)
            {
                var project = OpenProjectFile(dlg.FileName, false);

                if (project != null)
                {
                    var vm = new ImportProjectTabViewVM(project.Tabs, Path.GetFileNameWithoutExtension(dlg.FileName));
                    _notification.ShowModalDialog<ImportProjectTabViewVM, ImportProjectTabView>(vm, (x) =>
                    {
                        project.Tabs.Clear();
                        project.Tabs.AddRange(vm.Tabs.SynchedSource.ToList());
                        LoadProject(project, true);

                    }, () => { });
                }
            }
        }

        #endregion

        #region IStudioModuleVM

        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();
            //_singleControllers.ToList().ForEach(x => x.Value.ChangeRenderMode(true));
        }

        public override void OnNavigatedFrom()
        {
            base.OnNavigatedFrom();
            //_singleControllers.ToList().ForEach(x => x.Value.ChangeRenderMode(false));
        }

        public override void OnShuttingDown()
        {
            InvokeUINow(() =>
            {
                _settings.LastTechProjectFile = _lastTechProjectFile;
            });
        }

        public override void OnApplicationReady()
        {

        }

        #endregion

        #region Hardware Configuration

        private void SyncHardwareConfiguration()
        {
            var elements = Tabs.SelectMany(x => x.Elements).ToList();

            if (MachineOperator != null && MachineOperator.CurrentHardwareConfiguration != null)
            {
                var config = MachineOperator.CurrentHardwareConfiguration;

                foreach (var motorConfig in config.Motors)
                {
                    var itemConfig = MotorItem.MotorConfigurations.SingleOrDefault(x => x.HardwareMotorType.Code == motorConfig.HardwareMotorType.ToInt32());

                    if (itemConfig != null)
                    {
                        motorConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var pidConfig in config.PidControls)
                {
                    var itemConfig = PidItem.PidConfigurations.SingleOrDefault(x => x.HardwarePidControlType.Code == pidConfig.HardwarePidControlType.ToInt32());

                    if (itemConfig != null)
                    {
                        pidConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var winderConfig in config.Winders)
                {
                    var itemConfig = WinderItem.WinderConfigurations.SingleOrDefault(x => x.HardwareWinderType.Code == winderConfig.HardwareWinderType.ToInt32());

                    if (itemConfig != null)
                    {
                        winderConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var dancerConfig in config.Dancers)
                {
                    var itemConfig = DancerItem.DancerConfigurations.SingleOrDefault(x => x.HardwareDancerType.Code == dancerConfig.HardwareDancerType.ToInt32());

                    if (itemConfig != null)
                    {
                        dancerConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var speedSensorConfig in config.SpeedSensors)
                {
                    var itemConfig = SpeedSensorItem.SpeedSensorConfigurations.SingleOrDefault(x => x.HardwareSpeedSensorType.Code == speedSensorConfig.HardwareSpeedSensorType.ToInt32());

                    if (itemConfig != null)
                    {
                        speedSensorConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var blowerConfig in config.Blowers)
                {
                    var itemConfig = BlowerItem.BlowerConfigurations.SingleOrDefault(x => x.HardwareBlowerType.Code == blowerConfig.HardwareBlowerType.ToInt32());

                    if (itemConfig != null)
                    {
                        blowerConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var breakSensorConfig in config.BreakSensors)
                {
                    var itemConfig = BreakSensorItem.BreakSensorConfigurations.SingleOrDefault(x => x.HardwareBreakSensorType.Code == breakSensorConfig.HardwareBreakSensorType.ToInt32());

                    if (itemConfig != null)
                    {
                        breakSensorConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                _notification.ShowInfo("Visual elements synced to the last uploaded hardware configuration.");
            }
            else
            {
                ResetHardwareConfiguration();
            }
        }

        private async void UploadHardwareConfiguration()
        {
            if (MachineOperator != null)
            {
                using (_notification.PushTaskItem("Uploading hardware configuration..."))
                {
                    try
                    {
                        HardwareVersion hw = null;
                        Configuration config = null;

                        await Task.Factory.StartNew(() =>
                        {
                            using (ObservablesContext db = ObservablesContext.CreateDefault())
                            {
                                config = db.Adapter.GetConfiguration(x => x.Guid == ApplicationManager.Machine.ConfigurationGuid);
                                hw = db.Adapter.GetHardwareVersionByMachine(ApplicationManager.Machine.Guid).Clone();
                            }
                        });

                        foreach (var motorConfig in hw.HardwareMotors)
                        {
                            var itemConfig = MotorItem.MotorConfigurations.SingleOrDefault(x => x.HardwareMotorType.Code == motorConfig.HardwareMotorType.Code);

                            if (itemConfig != null)
                            {
                                itemConfig.MapPrimitivesTo(motorConfig);
                            }
                        }

                        foreach (var pidConfig in hw.HardwarePidControls)
                        {
                            var itemConfig = PidItem.PidConfigurations.SingleOrDefault(x => x.HardwarePidControlType.Code == pidConfig.HardwarePidControlType.Code);

                            if (itemConfig != null)
                            {
                                itemConfig.MapPrimitivesTo(pidConfig);
                            }
                        }

                        foreach (var winderConfig in hw.HardwareWinders)
                        {
                            var itemConfig = WinderItem.WinderConfigurations.SingleOrDefault(x => x.HardwareWinderType.Code == winderConfig.HardwareWinderType.Code);

                            if (itemConfig != null)
                            {
                                itemConfig.MapPrimitivesTo(winderConfig);
                            }
                        }

                        foreach (var dancerConfig in hw.HardwareDancers)
                        {
                            var itemConfig = DancerItem.DancerConfigurations.SingleOrDefault(x => x.HardwareDancerType.Code == dancerConfig.HardwareDancerType.Code);

                            if (itemConfig != null)
                            {
                                itemConfig.MapPrimitivesTo(dancerConfig);
                            }
                        }

                        foreach (var speedSensorConfig in hw.HardwareSpeedSensors)
                        {
                            var itemConfig = SpeedSensorItem.SpeedSensorConfigurations.SingleOrDefault(x => x.HardwareSpeedSensorType.Code == speedSensorConfig.HardwareSpeedSensorType.Code);

                            if (itemConfig != null)
                            {
                                itemConfig.MapPrimitivesTo(speedSensorConfig);
                            }
                        }

                        foreach (var blowerConfig in hw.HardwareBlowers)
                        {
                            var itemConfig = BlowerItem.BlowerConfigurations.SingleOrDefault(x => x.HardwareBlowerType.Code == blowerConfig.HardwareBlowerType.Code);

                            if (itemConfig != null)
                            {
                                itemConfig.MapPrimitivesTo(blowerConfig);
                            }
                        }

                        foreach (var breakSensorConfig in hw.HardwareBreakSensors)
                        {
                            var itemConfig = BreakSensorItem.BreakSensorConfigurations.SingleOrDefault(x => x.HardwareBreakSensorType.Code == breakSensorConfig.HardwareBreakSensorType.Code);

                            if (itemConfig != null)
                            {
                                itemConfig.MapPrimitivesTo(breakSensorConfig);
                            }
                        }

                        await MachineOperator.UploadHardwareConfiguration(hw, config);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error uploading hardware configuration.");
                        _notification.ShowError("An error occurred while trying to upload the hardware configuration." + Environment.NewLine + ex.Message);
                    }
                }
            }
        }

        private async void UploadPartialHardwareConfiguration()
        {
            if (MachineOperator != null)
            {
                if (_notification.ShowQuestion("This will upload only visible elements across all tabs as a hardware configuration package. Are you sure?"))
                {
                    using (_notification.PushTaskItem("Uploading partial hardware configuration..."))
                    {
                        try
                        {
                            HardwareVersion hw = new HardwareVersion();
                            hw.Name = "Partial HW Configuration";
                            hw.Version = 1;

                            Configuration config = null;

                            foreach (var element in Tabs.SelectMany(x => x.Elements).ToList())
                            {
                                var item = element.HostedElement as TechItem;

                                if (item is MotorItem)
                                {
                                    hw.HardwareMotors.Add((item as MotorItem).HardwareMotor);
                                }
                                else if (item is DancerItem)
                                {
                                    hw.HardwareDancers.Add((item as DancerItem).HardwareDancer);
                                }
                                else if (item is PidItem)
                                {
                                    hw.HardwarePidControls.Add((item as PidItem).HardwarePid);
                                }
                                else if (item is BlowerItem)
                                {
                                    hw.HardwareBlowers.Add((item as BlowerItem).HardwareBlower);
                                }
                                else if (item is BreakSensorItem)
                                {
                                    hw.HardwareBreakSensors.Add((item as BreakSensorItem).HardwareBreakSensor);
                                }
                                else if (item is SpeedSensorItem)
                                {
                                    hw.HardwareSpeedSensors.Add((item as SpeedSensorItem).HardwareSpeedSensor);
                                }
                                else if (item is WinderItem)
                                {
                                    hw.HardwareWinders.Add((item as WinderItem).HardwareWinder);
                                }
                            }

                            await Task.Factory.StartNew(() =>
                            {
                                using (ObservablesContext db = ObservablesContext.CreateDefault())
                                {
                                    config = db.Adapter.GetConfiguration(x => x.Guid == ApplicationManager.Machine.ConfigurationGuid).Clone();
                                }
                            });

                            await MachineOperator.UploadHardwareConfiguration(hw, config);
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, "Error uploading partial hardware configuration.");
                            _notification.ShowError("An error occurred while trying to upload the partial hardware configuration." + Environment.NewLine + ex.Message);
                        }
                    }
                }
            }
        }

        private async void ResetHardwareConfiguration(bool showMessage = true)
        {
            if (MachineOperator != null)
            {
                ObservablesContext db = ObservablesContext.CreateDefault();
                ObservablesContextAdapter adapter = new ObservablesContextAdapter(db);

                HardwareVersion hw = null;

                await Task.Factory.StartNew(() =>
                {
                    hw = adapter.GetHardwareVersionByMachine(ApplicationManager.Machine.Guid);
                });

                foreach (var motorConfig in hw.HardwareMotors)
                {
                    var itemConfig = MotorItem.MotorConfigurations.SingleOrDefault(x => x.HardwareMotorType.Code == motorConfig.HardwareMotorType.Code);

                    if (itemConfig != null)
                    {
                        motorConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var pidConfig in hw.HardwarePidControls)
                {
                    var itemConfig = PidItem.PidConfigurations.SingleOrDefault(x => x.HardwarePidControlType.Code == pidConfig.HardwarePidControlType.Code);

                    if (itemConfig != null)
                    {
                        pidConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var winderConfig in hw.HardwareWinders)
                {
                    var itemConfig = WinderItem.WinderConfigurations.SingleOrDefault(x => x.HardwareWinderType.Code == winderConfig.HardwareWinderType.Code);

                    if (itemConfig != null)
                    {
                        winderConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var dancerConfig in hw.HardwareDancers)
                {
                    var itemConfig = DancerItem.DancerConfigurations.SingleOrDefault(x => x.HardwareDancerType.Code == dancerConfig.HardwareDancerType.Code);

                    if (itemConfig != null)
                    {
                        dancerConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var speedSensorConfig in hw.HardwareSpeedSensors)
                {
                    var itemConfig = SpeedSensorItem.SpeedSensorConfigurations.SingleOrDefault(x => x.HardwareSpeedSensorType.Code == speedSensorConfig.HardwareSpeedSensorType.Code);

                    if (itemConfig != null)
                    {
                        speedSensorConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var blowerSensorConfig in hw.HardwareBlowers)
                {
                    var itemConfig = BlowerItem.BlowerConfigurations.SingleOrDefault(x => x.HardwareBlowerType.Code == blowerSensorConfig.HardwareBlowerType.Code);

                    if (itemConfig != null)
                    {
                        blowerSensorConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                foreach (var breakSensorConfig in hw.HardwareBreakSensors)
                {
                    var itemConfig = BreakSensorItem.BreakSensorConfigurations.SingleOrDefault(x => x.HardwareBreakSensorType.Code == breakSensorConfig.HardwareBreakSensorType.Code);

                    if (itemConfig != null)
                    {
                        breakSensorConfig.MapPrimitivesTo(itemConfig);
                    }
                }

                if (showMessage)
                {
                    _notification.ShowInfo("Visual elements synced to hardware version " + hw.Name + ", " + hw.Version + ".");
                }
            }
        }

        #endregion

        #region Graphs

        public void ClearAllGraphs()
        {
            _start_time = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            _last_time = DateTime.Now;

            foreach (var controller in _singleControllers)
            {
                controller.Value.Clear();
            }

            foreach (var controller in _multiControllers)
            {
                controller.Value.Clear();
            }
        }

        #endregion
    }
}