/*******************************************************************************
* Copyright (C) 2016 Maxim Integrated Products, Inc., All rights Reserved.
* 
* This software is protected by copyright laws of the United States and
* of foreign countries. This material may also be protected by patent laws
* and technology transfer regulations of the United States and of foreign
* countries. This software is furnished under a license agreement and/or a
* nondisclosure agreement and may only be used or reproduced in accordance
* with the terms of those agreements. Dissemination of this information to
* any party or parties not specified in the license agreement and/or
* nondisclosure agreement is expressly prohibited.
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name of Maxim Integrated
* Products, Inc. shall not be used except as stated in the Maxim Integrated
* Products, Inc. Branding Policy.
*
* The mere transfer of this software does not imply any licenses
* of trade secrets, proprietary technology, copyrights, patents,
* trademarks, maskwork rights, or any other form of intellectual
* property whatsoever. Maxim Integrated Products, Inc. retains all
* ownership rights.
*******************************************************************************
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Globalization;

using HealthSensorPlatform.View;
using Maxim.CustomControls;
using Maxim.Utility;

namespace HealthSensorPlatform.Presenter
{
    class RegisterExportPresenter
    {
        IRegisterExportView exportView;
        IFormView hspMainForm;
        List<RegisterView> registerModels;

        Dictionary<string, RegisterView> registerModelDict;

        FileLog registerDataFile;
        FileCsvReader fileReader;

        public RegisterExportPresenter(IFormView hspMainForm, IRegisterExportView exportView, List<RegisterView> registerModels)
        {
            this.exportView = exportView;
            this.registerModels = registerModels;
            this.hspMainForm = hspMainForm;

            exportView.SelectionComplete += new EventHandler<CompleteEventArgs>(OnSelectionComplete);

            hspMainForm.RegisterExport += new EventHandler<EventArgs>(OnRegisterExport);
            hspMainForm.RegisterImport += new EventHandler<EventArgs>(OnRegisterImport);
            hspMainForm.Connected += new EventHandler<EventArgs>(OnConnected);

            registerDataFile = new FileLog();
            fileReader = new FileCsvReader();

            registerModelDict = new Dictionary<string, RegisterView>();

            foreach (RegisterView rV in registerModels)
            {
                registerModelDict.Add(rV.DeviceName, rV);
                if (rV.DeviceName == "MAX30001")
                    registerModelDict.Add("MAX30003", rV); // add a second reference for MAX30003
            }

        }

        public List<string> GetDeviceNames()
        {
            List<string> devices = new List<string>();

            foreach(RegisterView device in registerModels)
            {
                devices.Add(device.DeviceName);
            }

            return devices;
        }

        private void OnConnected(object sender, EventArgs e)
        {
            exportView.Devices = GetDeviceNames();
            exportView.SelectedDevices = new List<string>();
        }

        private void OnRegisterExport(object sender, EventArgs e)
        {
            exportView.Show();            
        }

        private void OnRegisterImport(object sender, EventArgs e)
        {
            char[] hexSymbol = new char[] { 'h', 'H' };
            bool ok = true;

            if (fileReader.OpenCSVFile())
            {
                    while (fileReader.Peek() > 0)
                    {
                        string[] elements = fileReader.ReadLineElements();
                        string registerAddress;
                        string registerValue;

                        // End of data
                        if (elements[0].Contains('%') || elements[0] == String.Empty)
                            continue;

                        if (ok = registerModelDict.ContainsKey(elements[0]))
                        {
                            RegisterView view = registerModelDict[elements[0]]; // Look up in dictionary

                            registerAddress = elements[1].TrimEnd(hexSymbol);
                            registerValue = elements[3].TrimEnd(hexSymbol);

                            RPCSupport.DeviceSupport.RegisterInfo reg = view.RegisterAddress(Int32.Parse(registerAddress, NumberStyles.HexNumber));

                            if (reg.type == RPCSupport.DeviceSupport.RegisterInfo.RegisterType.None)
                                view.WriteRegister(reg, Int32.Parse(registerValue, NumberStyles.HexNumber));
                        }
                        else
                            break;
                }

                fileReader.Close();

                if (ok)
                {
                    hspMainForm.UpdateRegisters();
                    hspMainForm.MessageBoxShow("Register load complete", "Register Import/Export");
                }
                else
                {
                    hspMainForm.MessageBoxShow("Register load failed, file format incorrect", "Register Import/Export");
                }
            }
        }

        private void OnSelectionComplete(object sender, CompleteEventArgs e)
        {
            List<string> devices = exportView.SelectedDevices;

            if (e.Complete == true) // Successful device selection
            {
                if (registerDataFile.SelectCSVFile("hsp-register_data")) // Successful file selection
                {
                    foreach (string device in devices) // Match string with RegisterView
                    {
                        RegisterView regView = registerModelDict[device]; // Find register view corresponding with device name

                        regView.ReadAll(); // Update register values
                        registerDataFile.WriteLine("% Device, Address (hex), Name, Value (hex)");
                        registerDataFile.WriteLine(regView.RegistersToString()); // Do the Export
                        registerDataFile.WriteLine("%"); // End of register data
                    }

                    registerDataFile.Close();

                    hspMainForm.MessageBoxShow("Register save complete", "Register Import/Export");
                }
            }

        }

    }
}
