using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Siemens.Engineering;
using Siemens.Engineering.SW;
using Siemens.Engineering.HW;
using System.IO;
using Siemens.Engineering.HW.Features;
using Siemens.Engineering.Hmi;


namespace TIAOpennessGenerator
{
    public partial class TIAGenerator : Form
    {
        private static TiaPortalProcess _tiaProcess;

        public TiaPortal MyTiaPortal
        {
            get; set;
        }

        public Project MyProject
        {
            get; set;
        }

        public Device MyDevice
        {
            get; set;
        }
        
        Generator generator = new Generator();

        public TreeNode Device;

        int i = 0;

        public TIAGenerator()
        {
            InitializeComponent();

            Receipt.PathSource = txt_SourcePath.Text;
            Receipt.PathObject = txt_ObjectPath.Text;
        }

        //Start TIA Portalu
        private void Strat_Button_Click(object sender, EventArgs e)
        {
            if (rdb_WithoutUI.Checked == true)
            {
                MyTiaPortal = new TiaPortal(TiaPortalMode.WithoutUserInterface);
                txt_Status.Text = "TIA Portal started without user interface" + Environment.NewLine + txt_Status.Text;
                //txt_Status.Text = "TIA Portal started without user interface";
                //listBox1.Items.Add("TIA Portal started without user interface");
                _tiaProcess = TiaPortal.GetProcesses()[0];
            }
            else
            {
                MyTiaPortal = new TiaPortal(TiaPortalMode.WithUserInterface);
                txt_Status.Text = "TIA Portal started with user interface" + Environment.NewLine + txt_Status.Text;
                //txt_Status.Text = "TIA Portal started with user interface";
                //listBox1.Items.Add("TIA Portal started with user interface");
            }

            Dispose_Button.Enabled = true;
            New_Button.Enabled = true;
            Open_Button.Enabled = true;

            Strat_Button.Enabled = false;
            Connect_Button.Enabled = false;
        }

        //Ukončení aktivní instance TiaPortal
        private void Dispose_Button_Click(object sender, EventArgs e)
        {
            MyTiaPortal.Dispose();
            txt_Status.Text = "TIA Portal disposed" + Environment.NewLine + txt_Status.Text;
            //txt_Status.Text = "TIA Portal disposed";
            //listBox1.Items.Add("TIA Portal disposed");

            Strat_Button.Enabled = true;
            Connect_Button.Enabled = true;

            Dispose_Button.Enabled = false;            
            New_Button.Enabled = false;
            Open_Button.Enabled = false;
            Save_Button.Enabled = false;
            Close_Button.Enabled = false;
            PLCGenerate_Button.Enabled = false;
            HMIGenerate_Button.Enabled = false;
            AddDevice_Button.Enabled = false;

        }

        //Připojení k již otevřenému projektu
        private void Connect_Button_Click(object sender, EventArgs e)
        {
            Connect_Button.Enabled = false;

            IList<TiaPortalProcess> processes = TiaPortal.GetProcesses();
            switch (processes.Count)
            {
                case 1:
                    _tiaProcess = processes[0];
                    MyTiaPortal = _tiaProcess.Attach();

                    if (MyTiaPortal.Projects.Count <= 0)
                    {
                        txt_Status.Text = "No TIA Portal Project was found!" + Environment.NewLine + txt_Status.Text;

                        //txt_Status.Text = "No TIA Portal Project was found!";
                        //listBox1.Items.Add("No TIA Portal Project was found!");
                        Connect_Button.Enabled = true;
                        return;
                    }
                    MyProject = MyTiaPortal.Projects[0];
                    break;
                case 0:
                    txt_Status.Text = "No running instance of TIA Portal was found" + Environment.NewLine + txt_Status.Text;

                    //txt_Status.Text = "No running instance of TIA Portal was found!";
                    //listBox1.Items.Add("No running instance of TIA Portal was found!");
                    Connect_Button.Enabled = true;
                    return;
                default:
                    txt_Status.Text = "More than one running instance of TIA Portal was found!" + Environment.NewLine + txt_Status.Text;

                    //txt_Status.Text = "More than one running instance of TIA Portal was found!";
                    //listBox1.Items.Add("More than one running instance of TIA Portal was found!");
                    Connect_Button.Enabled = true;
                    return;
            }
            txt_Status.Text = "Connect is successfull!" + Environment.NewLine + txt_Status.Text;

            //txt_Status.Text = "Connect is successfull!";
            //listBox1.Items.Add("Connect is successfull!");

            Dispose_Button.Enabled = true;
            Save_Button.Enabled = true;
            Close_Button.Enabled = true;
            PLCGenerate_Button.Enabled = true;
            HMIGenerate_Button.Enabled = true;
            AddDevice_Button.Enabled = true;

            Strat_Button.Enabled = false;
            Connect_Button.Enabled = false;

            
        }

        //Generování PLC
        private void PLCGenerate_Button_Click(object sender, EventArgs e)
        {
            Receipt.PathSource = txt_SourcePath.Text;
            Receipt.PathObject = txt_ObjectPath.Text;
            //generator.Generate(MyProject, PathObject);
            generator.GeneratePLC(MyProject);
            txt_Status.Text = "PLC program was successfully generated!" + Environment.NewLine + txt_Status.Text;
        }

        //Generování HMI
        private void HMIGenerate_Button_Click(object sender, EventArgs e)
        {
            Receipt.PathSource = txt_SourcePath.Text;
            Receipt.PathObject = txt_ObjectPath.Text;

            generator.GenerateHMI(MyProject);
            txt_Status.Text = "HMI program was successfully generated" + Environment.NewLine + txt_Status.Text;
        }

        //Zavrení projektu
        private void Close_Button_Click(object sender, EventArgs e)
        {
            MyProject.Close();
            txt_Status.Text = "Project closed" + Environment.NewLine + txt_Status.Text;

            Open_Button.Enabled = true;
            New_Button.Enabled = true;

            Close_Button.Enabled = false;
            Save_Button.Enabled = false;
            HMIGenerate_Button.Enabled = false;
            PLCGenerate_Button.Enabled = false;
            AddDevice_Button.Enabled = false;
        }

        //Vytvoření nového projektu
        private void New_Button_Click(object sender, EventArgs e)
        {
            Receipt.PathObject = txt_ObjectPath.Text;

            ProjectComposition projectComposition = MyTiaPortal.Projects;
            DirectoryInfo targetDirectory = new DirectoryInfo(Receipt.PathObject + @"TiaProjects\" + txt_ProjectName.Text);

            if (!targetDirectory.Exists)
            {
                targetDirectory = new DirectoryInfo(Receipt.PathObject + "TiaProjects");
                // Create a project
                MyProject = projectComposition.Create(targetDirectory, txt_ProjectName.Text);

                txt_Status.Text = "Project " + txt_ProjectName.Text + " was created" + Environment.NewLine + txt_Status.Text;

                AddDevice_Button.Enabled = true;
                PLCGenerate_Button.Enabled = true;
                HMIGenerate_Button.Enabled = true;
                Close_Button.Enabled = true;
                Save_Button.Enabled = true;

                Open_Button.Enabled = false;
                New_Button.Enabled = false;
            }
            else
                txt_Status.Text = "Project " + txt_ProjectName.Text + " already exists" + Environment.NewLine + txt_Status.Text;
        }


        //Nalezení a otevření projektu
        private void Open_Button_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileSearch = new OpenFileDialog();

            fileSearch.Filter = "*.ap14|*.ap14";
            fileSearch.RestoreDirectory = true;
            fileSearch.ShowDialog();

            string ProjectPath = fileSearch.FileName.ToString();

            if (string.IsNullOrEmpty(ProjectPath) == false)
            {
                OpenProject(ProjectPath);
            }
        }


        //Otevření projektu
        private void OpenProject(string ProjectPath)
        {
            try
            {
                MyProject = MyTiaPortal.Projects.Open(new FileInfo(ProjectPath));
                txt_Status.Text = "Project " + ProjectPath + " opened" + Environment.NewLine + txt_Status.Text;

                AddDevice_Button.Enabled = true;
                PLCGenerate_Button.Enabled = true;
                HMIGenerate_Button.Enabled = true;
                Close_Button.Enabled = true;
                Save_Button.Enabled = true;

                Open_Button.Enabled = false;
                New_Button.Enabled = false;
            }
            catch (Exception ex)
            {
                txt_Status.Text = "Error while opening project" + ex.Message + Environment.NewLine + txt_Status.Text;
            }
        }

        //Ulozeni projektu
        private void Save_Button_Click(object sender, EventArgs e)
        {
            MyProject.Save();
            txt_Status.Text = "Project saved" + Environment.NewLine + txt_Status.Text;
        }

        //Výběr hardwaru
        private void AddDevice_Button_Click(object sender, EventArgs e)
        {
            AddDevice addDevice = new AddDevice(this);
            addDevice.Show();
        }

        //Přidání hardwaru
        public void AddDevice()
        {
            string OrderNumber;
            string Version;

            //Přeložit texty
            Version = Device.Text;
            OrderNumber = Device.Parent.Text;

            string MLFB = "OrderNumber:" + OrderNumber + "/" + Version;

            string name = txt_DeviceName.Text;
            string devname = "station" + txt_DeviceName.Text;
            bool found = false;
            foreach (Device device in MyProject.Devices)
            {
                DeviceItemComposition deviceItemAggregation = device.DeviceItems;
                foreach (DeviceItem deviceItem in deviceItemAggregation)
                {
                    if (deviceItem.Name == devname || device.Name == devname)
                    {
                        SoftwareContainer softwareContainer = deviceItem.GetService<SoftwareContainer>();
                        if (softwareContainer != null)
                        {
                            if (softwareContainer.Software is PlcSoftware)
                            {
                                PlcSoftware controllerTarget = softwareContainer.Software as PlcSoftware;
                                if (controllerTarget != null)
                                {
                                    found = true;

                                }
                            }
                            if (softwareContainer.Software is HmiTarget)
                            {
                                HmiTarget hmitarget = softwareContainer.Software as HmiTarget;
                                if (hmitarget != null)
                                {
                                    found = true;

                                }

                            }
                        }
                    }
                }
            }
            if (found == true)
            {
                txt_Status.Text = "Device " + txt_DeviceName.Text + " already exists" + Environment.NewLine + txt_Status.Text;
            }
            else
            {
                //Přidání zařízení
                MyDevice = MyProject.Devices.CreateWithItem(MLFB, name, devname);
                //MyDevice = MyProject.Devices.CreateWithItem(OrderNumber + "/" + Version, name, devname);

                txt_Status.Text = "Add Device Name: " + name + " with Order Number: " + OrderNumber + " and Firmware Version: " + Version + Environment.NewLine + txt_Status.Text;
            }
        }

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









        //Z Project chybí ještě Open, Save, Close, New

    }
}
