using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

// Added using statements.
using System.Xml.Linq;
using System.IO;
using System.Reflection;
using System.IO.IsolatedStorage;

namespace SilverlightXML
{
    public partial class MainPage : UserControl
    {
        // Define an isolated storage location for this application.
        IsolatedStorageFile ISO;

        // Create a global variable used to hold the directory
        // for the settings file.
        String SettingsDirectory;

        // Create a global variable containing the name and
        // location of the settings file.
        String SettingsFile;

        public MainPage()
        {
            InitializeComponent();

            // Obtain the configuration information for this application.
            Object[] Configuration = 
                Assembly.GetExecutingAssembly().GetCustomAttributes(false);

            // Obtain the company name.
            String CompanyName = "Company";
            foreach (var Value in Configuration)
                if (Value.GetType() == typeof(AssemblyCompanyAttribute))
                {
                    CompanyName = ((AssemblyCompanyAttribute)Value).Company;
                    break;
                }

            // Obtain the executable name.
            String Title = "Title";
            foreach (var Value in Configuration)
                if (Value.GetType() == typeof(AssemblyTitleAttribute))
                {
                    Title = ((AssemblyTitleAttribute)Value).Title;
                    break;
                }

            // Obtain the version number.
            String Version = "0.0.0.0";
            foreach (var Value in Configuration)
                if (Value.GetType() == typeof(AssemblyFileVersionAttribute))
                {
                    Version = ((AssemblyFileVersionAttribute)Value).Version;
                    break;
                }

            // Create an isolated storage instance for the application data.
            ISO = IsolatedStorageFile.GetUserStoreForApplication();

            // Store the location of the settings directory.
            SettingsDirectory = 
                System.IO.Path.Combine(CompanyName, Title, Version);

            // Store the location of the settings file.
            SettingsFile = SettingsDirectory + "\\Settings.XML";

            // Check for a settings file.
            if (ISO.FileExists(SettingsFile))
            {
                // Obtain access to the file.
                IsolatedStorageFileStream Input = 
                    new IsolatedStorageFileStream(
                        SettingsFile, FileMode.Open, ISO);

                // Try to perform this task. If it fails, use the default settings.
                try
                {

                    // Load the file containing the settings.
                    XDocument SettingData = XDocument.Load(Input);

                    // Change the control settings to match the file settings.
                    txtMessage.Text = SettingData.Root.Element("txtMessage").Value;
                    chkChecked.IsChecked = 
                        Boolean.Parse(SettingData.Root.Element("chkChecked").Value);

                    // Close the input.
                    Input.Close();

                }
                catch
                {
                    // Close the damaged file.
                    Input.Close();

                    // Delete the damaged file.
                    ISO.DeleteFile(SettingsFile);
                }
            }
        }

        private void SaveSettings()
        {
            // Create a document to hold the settings.
            XDocument SettingData = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("Settings",
                    new XElement("txtMessage", txtMessage.Text),
                    new XElement("chkChecked", chkChecked.IsChecked)));

            // Create the folder used to store the data if necessary.
            if (!ISO.DirectoryExists(SettingsDirectory))
                ISO.CreateDirectory(SettingsDirectory);

            // Try this procedure out and simply fail if it isn't permitted.
            try
            {

                // Create the required file stream.
                IsolatedStorageFileStream Output =
                    new IsolatedStorageFileStream(
                        SettingsFile, FileMode.OpenOrCreate, ISO);

                // Save the settings to disk.
                SettingData.Save(Output);

                // Close the output.
                Output.Close();
            }
            catch
            {
                // Display an error message.
                MessageBox.Show("Unable to save settings!");
            }
        }

        private void txtMessage_LostFocus(object sender, RoutedEventArgs e)
        {
            // Save the settings.
            SaveSettings();
            System.Diagnostics.Debug.WriteLine("In txtMessage_LostFocus");
        }

        private void chkChecked_LostFocus(object sender, RoutedEventArgs e)
        {
            // Save the settings.
            SaveSettings();
            System.Diagnostics.Debug.WriteLine("In chkChecked_LostFocus");
        }

        private void chkChecked_Checked(object sender, RoutedEventArgs e)
        {
            // Save the settings.
            SaveSettings();
            System.Diagnostics.Debug.WriteLine("In chkChecked_Checked");
        }
    }
}
