using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;

using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;

namespace RSSReaderInstaller
{
    [RunInstaller(true)]
    public partial class RSSReaderInstaller : Installer
    {
        const string INI_FILE = @"setup.ini";

        public RSSReaderInstaller()
        {
            InitializeComponent();
            this.AfterInstall += new InstallEventHandler(RSSReaderInstaller_AfterInstall);
            this.AfterUninstall += new InstallEventHandler(RSSReaderInstaller_AfterUninstall);
        }

        void RSSReaderInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            //---to be executed when the application is installed---
            string ceAppPath = GetWindowsCeApplicationManager();
            if (ceAppPath == String.Empty)
                return;
            Process.Start(ceAppPath, GetIniPath());
        }

        void RSSReaderInstaller_AfterUninstall(object sender, InstallEventArgs e)
        {
            //---to be executed when the application is uninstalled---
            string ceAppPath = GetWindowsCeApplicationManager();
            if (ceAppPath == String.Empty)
                return;
            Process.Start(ceAppPath, String.Empty);
        }

        private string GetWindowsCeApplicationManager()
        {
            //---sprawdzenie, czy zainstalowany jest Menedżer aplikacji Windows CE---
            string ceAppPath = KeyExists();
            if (ceAppPath == String.Empty)
            {
                MessageBox.Show("Menedżer aplikacji Windows CE nie jest zainstalowany",
                                "Instalacja", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return String.Empty;
            }
            else
                return ceAppPath;
        }

        private string GetIniPath()
        {
            //---get the path of the .ini file---
            return "\"" +
               Path.Combine(Path.GetDirectoryName(
               System.Reflection.Assembly.
               GetExecutingAssembly().Location), INI_FILE) + "\"";
        }

        private string KeyExists()
        {
            //---get the path to the Windows CE App Manager from the registry---
            RegistryKey key =
                Registry.LocalMachine.OpenSubKey(
                @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\CEAPPMGR.EXE");
            if (key == null)
                return String.Empty;
            else
                return key.GetValue(String.Empty, String.Empty).ToString();
        }
    }
}
