// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2021 Torsten Schache, Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Hiperscan.SGS;
using Hiperscan.Unix;

namespace Hiperscan.Extensions.ApoIdent
{
    public partial class ApoIdentApplication
    {
        private void InitConnection()
        {
            this.Control.ConnectionIsInitializing = true;

            lock (this.Control.Transaction)
            {

                try
                {
                    Console.WriteLine("Init connection device - IdentModule...");

                    this.Control.ConnectionSuccess = false;
                    this.InitCombinedFinder();
                    this.Control.Busy = true;
                    this.Update(ApoIdentApplicationState.ConnectionStart);

                    this.Control.Host.DeviceList.DeviceAdded -= this.OnDeviceAdded;
                    this.Control.Host.DeviceList.DeviceRemoved -= this.OnDeviceRemoved;

                    int major = Int32.Parse(Plugin.version.Split(new char[] { '.' })[0]);
                    int minor = Int32.Parse(Plugin.version.Split(new char[] { '.' })[1]);

                    ApoIdentApplicationState state = ApoIdentApplicationState.None;

                    Console.WriteLine("Init IdentModule...");

                    state = this.IdentServerClient.Start(new System.Version(major, minor),
                                                         this.Control.Host.IsRelease, true);

                    if (state == ApoIdentApplicationState.ConnectionStartIdentServerFailed ||
                        state == ApoIdentApplicationState.ConnectionIdentServerRefused)
                    {
                        Thread.Sleep(1000);
                        state = this.IdentServerClient.Start(new System.Version(major, minor),
                                                             this.Control.Host.IsRelease, false);
                    }

                    this.InitSubstanceManagement();

                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Control.Busy = false;
                        this.Update(state, this.IdentServerClient.ErrorMessage, this.IdentServerClient.Exception);
                        return;
                    }

                    Console.WriteLine("\tChecking IdentModule release version... ");
                    state = this.IdentServerClient.CheckReleaseVersion();
                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Control.Busy = false;
                        this.Update(state, this.IdentServerClient.ErrorMessage, this.IdentServerClient.Exception);
                        return;
                    }

                    Console.WriteLine("\tInitializing instrument ...");
                    do
                    {
                        state = this.Finder.InitDevice(this.Control.Host.DeviceList, null);
                    }
                    while (state == ApoIdentApplicationState.ConnectionInitDeviceTryAgain);

                    this.Control.Host.DeviceList.DeviceAdded += this.OnDeviceAdded;
                    this.Control.Host.DeviceList.DeviceRemoved += this.OnDeviceRemoved;

                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Finder.Reset();
                        this.Control.Busy = false;
                        this.Update(state, this.Finder.ErrorMessage, this.Finder.Exception);
                        return;
                    }

                    this.Finder.Device.StateChanged += this.OnDeviceStateChanged;

                    Console.WriteLine("\tRegistering instrument at IdentModule ...");
                    state = this.IdentServerClient.RegisterDevice(this.Finder.Device);
                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Finder.Reset();
                        this.Control.Busy = false;
                        this.Update(state, this.IdentServerClient.ErrorMessage, this.IdentServerClient.Exception);
                        return;
                    }

                    Console.WriteLine("\tInitializing Finder ...");
                    state = this.Finder.InitFinder(ApoIdentApplication.GetSpectrumCreatorName());
                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Finder.Reset();
                        this.Control.Busy = false;
                        this.Update(state, this.Finder.ErrorMessage, this.Finder.Exception);
                        return;
                    }

                    this.InitFinderEvents();

                    Console.WriteLine("\tLoading data from identmodule ...");

                    state = this.IdentServerClient.LoadData(this.SubstanceManagement);
                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Finder.Reset();
                        this.Control.Busy = false;
                        this.Update(state, this.IdentServerClient.ErrorMessage, this.IdentServerClient.Exception);
                        return;
                    }

                    Configurations.ProfilePreferences current = this.Config.Profiles.Current;
                    foreach (Configurations.ProfilePreferences profile in this.Config.Profiles.AllProfiles.Values)
                    {
                        this.Config.Profiles.Current = profile;
                        this.Config.Profiles.Current.ReadNotMeasurableSubstances(this.IdentServerClient);
                        this.Config.Profiles.Current.ReadAddtionalInfos();
                    }
                    this.Config.Profiles.Current = current;
                    this.SubstanceManagement.InitModelExtension();
                    if (this.Config.Profiles.Current != null)
                        this.Finder.UpdateReferencingDir(this.Config.Profiles.Current.ArchiveMissing);

                    Console.WriteLine("\tWarm-up ...");
                    state = this.Finder.DeviceWarmup();
                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Finder.Reset();
                        this.Control.Busy = false;
                        this.Update(state, this.Finder.Warmup.Exception.Message, this.Finder.Warmup.Exception);
                        return;
                    }

                    Console.WriteLine("\tChecking IdentModule scanner lib... ");
                    //Ticket #35618 this.Scanner.Init(this.IdentServerClient.GetPpnList(), this.Finder.IsApoIdent1);
                    //this.ScanRecognizer.IsActive = this.Finder.IsApoIdent1 == false;
                    this.Scanner.Init(this.IdentServerClient.GetPpnList(), true);
                    this.ScanRecognizer.IsActive = false;

                    this.AddFinderInternalCalibrationEvents();
                    this.Finder.DeviceMode = Catalog.GetString("Ready");

                    Console.WriteLine("\tFinderButton ...");
                    this.Finder.InitFinderButton();
                    this.Finder.FinderButton.FinderButtonPressedHandler += this.OnFinderButtonActivated;

                    this.Control.ConnectionSuccess = true;
                    this.Control.Busy = false;
                    this.Update(ApoIdentApplicationState.ConnectionWarmupEnd);

                    if (this.Finder.QuitRequested)
                    {
                        Thread.Sleep(1000);
                        this.Exit();
                    }


                    state = this.IdentServerClient.CheckForPendingUpdate();
                    if (state != ApoIdentApplicationState.None)
                    {
                        this.Update(state);
                    }

                    this.CheckArchive();
                }
                catch (Exception ex)
                {
                    this.Control.Busy = false;
                    string message = String.Format(Catalog.GetString("Error while initializing Apo-Ident: {0}"), ex.Message);
                    this.Update(ApoIdentApplicationState.ConnectionUnknownError, message, ex);
                }
                finally
                {
                    this.PrepareProtocolSection();
                    this.Control.ConnectionIsInitializing = false;
                }
            }
        }
    }
}
