aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/PPCApplication/DefaultPPCApplicationManager.cs
blob: e75a0616ceb258a277dc7f8a1e60f4bf2bd809e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Entities;
using Tango.Integration.Operation;
using Tango.Settings;
using Tango.PPC.Common.Application;
using Tango.Core.DI;
using Tango.PPC.Common;
using System.Windows;
using Tango.Core;
using System.IO;
using Tango.Core.Helpers;
using Tango.PPC.Common.Modules;
using System.Windows.Threading;
using Tango.Transport.Adapters;
using Tango.PMR.Connection;
using Tango.PPC.Common.Connection;
using Tango.SQLExaminer;
using System.Data.SqlClient;

namespace Tango.PPC.UI.PPCApplication
{
    /// <summary>
    /// Represents the default PPC application manager.
    /// </summary>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    /// <seealso cref="Tango.PPC.Common.Application.IPPCApplicationManager" />
    public class DefaultPPCApplicationManager : ExtendedObject, IPPCApplicationManager
    {
        private List<PPCViewModel> _notifiedViewModels;
        private IMachineProvider _machineProvider;

        /// <summary>
        /// Occurs when the application has started.
        /// </summary>
        public event EventHandler ApplicationStarted;

        /// <summary>
        /// Occurs when all PPC modules are ready and initialized.
        /// </summary>
        public event EventHandler ModulesInitialized;

        /// <summary>
        /// Gets a value indicating whether the application is shutting down.
        /// </summary>
        public bool IsShuttingDown { get; private set; }

        /// <summary>
        /// Gets the application version.
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public string Version
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultPPCApplicationManager"/> class.
        /// </summary>
        public DefaultPPCApplicationManager(IMachineProvider machineProvider)
        {
            _machineProvider = machineProvider;

            if (!DesignMode)
            {
                _notifiedViewModels = new List<PPCViewModel>();

                PPCSettings settings = null;

                MainWindow.Instance.ContentRendered += async (_, __) =>
                {
                    ContentRendered?.Invoke(this, new EventArgs());

                    await Task.Factory.StartNew(() =>
                    {
                        //TODO: Use this in the future.

                        //#if DEBUG
                        //            DataSource = "localhost\\SQLEXPRESS";
                        //#else
                        //            DataBaseSettings.DefaultDataSource = Path.Combine(PathHelper.GetUserTangoFolder(), "DB", "Tango.db");
                        //#endif

                        if (!File.Exists(CoreSettings.DefaultDataBaseSource))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(CoreSettings.DefaultDataBaseSource));
                            File.Copy(Path.Combine(PathHelper.GetStartupPath(), "DB", "Tango.mdf"), CoreSettings.DefaultDataBaseSource);
                        }

                        settings = SettingsManager.Default.GetOrCreate<PPCSettings>();
                        var coreSettings = SettingsManager.Default.GetOrCreate<CoreSettings>();

                        if (!SettingsManager.Default.IsFileExists())
                        {
                            settings.Save();
                        }

                        if (settings.HasSetup)
                        {
                            ObservablesEntitiesAdapter.Instance.Initialize();
                        }
                    });


                    if (settings.HasSetup)
                    {
                        PostSetup();
                    }
                    else
                    {
                        SetupRequiredEventArgs args = new SetupRequiredEventArgs(() =>
                        {
                            Task.Factory.StartNew(() =>
                            {
                                ObservablesEntitiesAdapter.Instance.Initialize();

                                InvokeUI(() =>
                                {
                                    PostSetup();
                                });
                            });
                        });
                        SetupRequired?.Invoke(this, args);
                    }
                };
            }
        }

        private void PostSetup()
        {
            ApplicationStarted?.Invoke(this, new EventArgs());

            foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>())
            {
                if (!_notifiedViewModels.Contains(vm))
                {
                    vm.OnApplicationStarted();
                    _notifiedViewModels.Add(vm);
                }
            }

            TangoIOC.Default.GetInstanceWhenAvailable<IPPCModuleLoader>((loader) =>
            {
                loader.ModulesLoaded += (x, y) =>
                {
                    if (loader.UserModules.Count > 0)
                    {
                        if (loader.UserModules.ToList().Exists(m => !m.IsInitialized))
                        {
                            loader.UserModules.LastOrDefault().Initialized += (e, f) =>
                            {
                                FinalizeModuleInitialization();
                            };
                        }
                        else
                        {
                            FinalizeModuleInitialization();
                        }
                    }
                };
            });
        }

        private void FinalizeModuleInitialization()
        {
            foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>())
            {
                if (!_notifiedViewModels.Contains(vm))
                {
                    vm.OnApplicationStarted();
                    _notifiedViewModels.Add(vm);
                }
            }

            ModulesInitialized?.Invoke(this, new EventArgs());
            _machineProvider.Init();
            Ready?.Invoke(this, new EventArgs());
        }

        /// <summary>
        /// Shutdown the application.
        /// </summary>
        public void ShutDown()
        {
            IsShuttingDown = true;

            foreach (var vm in TangoIOC.Default.GetAllInstancesByBase<PPCViewModel>())
            {
                vm.OnApplicationShuttingDown();
            }
        }

        public event EventHandler Ready;
        public event EventHandler<SetupRequiredEventArgs> SetupRequired;
        public event EventHandler ContentRendered;
    }
}