/// <summary>Create and initialise form to edit existing message.</summary>
        /// <param name="_message">The text message to edit.</param>
        public NewEditMessage(TextMessage _message)
            : this(_message.FilePath, _message.Format)
        {
            message = _message;
            MessageStatus status = message.Status;
            //initialise controls with values, taking into account numbers with names in them
            string from = message.From;
            txtFrom.Text = from;
            if (!String.IsNullOrEmpty(from)) {
                string fromName = Contacts.RetrieveName(from);
                lblFromName.Text = fromName;
            }

            txtMessage.Text = message.MessageText;
            string to = message.To;
            txtTo.Text = to;
            if (!String.IsNullOrEmpty(to)) {
                string toName = Contacts.RetrieveName(to);
                lblToName.Text = toName;
            }

            DateTime dt = message.DateTime;
            dtpDate.Value = dt;
            dtpTime.Value = dt;
        }
        /// <summary>Initializes a new instance of the <see cref="TextMessageListViewItem"/> class.</summary>
        /// <param name="_message">The TextMessage whose details are to be displayed.</param>
        public TextMessageListViewItem(TextMessage _message)
            : base()
        {
            message = _message;
            format = message.Format;

            string toNamesAndNumbers = NamesAndNumbers(message.To);
            string fromNamesAndNumbers = NamesAndNumbers(message.From);
            string fromNumber = fromNamesAndNumbers;
            string toNumber = toNamesAndNumbers;

            //TODO: use Reflector to see the internals of new ListViewItem(string[]) - in regards to SubItems and the default item
            /*
            public ListViewItem(string[] items, int imageIndex) : this()
            {
            this.ImageIndexer.Index = imageIndex;
            if ((items != null) && (items.Length > 0))
            {
            this.subItems = new ListViewSubItem[items.Length];
            for (int i = 0; i < items.Length; i++)
            {
            this.subItems[i] = new ListViewSubItem(this, items[i]);
            }
            this.SubItemCount = items.Length;
            }
            }
            */

            ListViewSubItem fromNumberItem = new ListViewSubItem(this, fromNumber);
            fromNumberItem.Name = "FromNumber";
            SubItems.Add(fromNumberItem);
            ListViewSubItem messageItem = new ListViewSubItem(this, message.MessageText);
            messageItem.Name = "Message";
            SubItems.Add(messageItem);
            string dateString = message.DateTime.Date.ToShortDateString();
            ListViewSubItem dateItem = new ListViewSubItem(this, dateString);
            dateItem.Name = "Date";
            SubItems.Add(dateItem);
            string timeString = message.DateTime.TimeOfDay.ToString();
            ListViewSubItem timeItem = new ListViewSubItem(this, timeString);
            timeItem.Name = "Time";
            SubItems.Add(timeItem);
            ListViewSubItem toNumberItem = new ListViewSubItem(this, toNumber);
            toNumberItem.Name = "ToNumber";
            SubItems.Add(toNumberItem);
            ListViewSubItem fileNameItem = new ListViewSubItem(this, message.FileName);
            fileNameItem.Name = "FileName";
            SubItems.Add(fileNameItem);
            SubItems.RemoveAt(0);//remove initial default entry
        }
        private void btnOk_Click(object sender, System.EventArgs e)
        {
            string from = txtFrom.Text;
            string to = txtTo.Text;
            DateTime date = dtpDate.Value.Date;
            TimeSpan time = dtpTime.Value.TimeOfDay;
            date = date.Add(time);

            string messageText = txtMessage.Text;
            MessageStatus status = MessageStatus.Recieved;
            string number = String.Empty;
            if (!String.IsNullOrEmpty(from)) {
                number = from;
                status = MessageStatus.Recieved;
            } else if (!String.IsNullOrEmpty(to)) {
                number = to;
                status = MessageStatus.Sent;
            }
            bool isEditMode = message != null;
            message = TextMessage.CreateMessage(format, messageText, from, to, date, status, filePath);

            List<string> existingText = new List<string>();
            string[] newInfo = { from, to, date.ToShortDateString(), time.ToString(), messageText };

            //Get current info from exisiting file
            if (isEditMode) {
                StreamReader sr = new StreamReader(filePath);
                while (sr.Peek() != -1) {
                    existingText.Add(sr.ReadLine());
                }

                sr.Close();
            }

            //Write details to file.
            if (!TextMessage.WriteTextMessage(existingText, message, format)) {
                MessageBox.Show("There was an error in saving the file");
                DialogResult = DialogResult.Cancel;
            } else {
                DialogResult = DialogResult.OK;
                this.Close();
            }
        }
        /// <summary>Creates the message of the correct format.</summary>
        /// <param name="_format">The format.</param>
        /// <param name="_message">The message.</param>
        /// <param name="fromNumber">The from number.</param>
        /// <param name="toNumber">The to number.</param>
        /// <param name="_dateTime">The date and time.</param>
        /// <param name="_sentOrRecieved">The sent or recieved status.</param>
        /// <param name="_filePath">The file path.</param>
        /// <returns>The newly created message.</returns>
        public static TextMessage CreateMessage(MessageFormat _format, string _message, string fromNumber, string toNumber, DateTime _dateTime, MessageStatus _sentOrRecieved, string _filePath)
        {
            TextMessage result = new TextMessage(_format, _message, fromNumber, toNumber, _dateTime, _sentOrRecieved, _filePath);

            return result;
        }
        /// <summary>Writes the text message to a file, in Nokia format.</summary>
        /// <param name="existingText">Any existing text, usually read from the file before editing.</param>
        /// <param name="message">The message.</param>
        /// <returns>True, if sucessful, False otherwise.</returns>
        private static bool WriteNokiaMessageFile(List<string> existingText, TextMessage message)
        {
            int j = 0;
            bool inEditMode = existingText.Count > 0;
            bool success;

            StreamWriter sw = new StreamWriter(message.filePath);

            try {
                if (inEditMode) {
                    for (int i = 0; i < 7; i++) {
                        sw.WriteLine(existingText[j]);
                        j++;
                    }
                } else {
                    for (int i = 0; i < 7; i++) {
                        sw.WriteLine();
                        j++;
                    }
                }

                //From number line = 7
                string fromNumber = message.From;
                sw.WriteLine("TEL:" + fromNumber);//from
                j++;

                if (inEditMode) {
                    for (int i = 0; i < 5; i++) {
                        sw.WriteLine(existingText[j]);
                        j++;
                    }
                } else {
                    for (int i = 0; i < 5; i++) {
                        sw.WriteLine();
                        j++;
                    }
                }
                //To number line = 13
                string toNumber = message.To;
                sw.WriteLine("TEL:" + toNumber);
                j++;

                if (inEditMode) {
                    for (int i = 0; i < 3; i++) {
                        sw.WriteLine(existingText[j]);
                        j++;
                    }
                } else {
                    for (int i = 0; i < 3; i++) {
                        sw.WriteLine();
                        j++;
                    }
                }
                //Date line = 17
                sw.WriteLine("Date:" + message.DateTime.ToShortDateString() + " " + message.DateTime.ToLongTimeString());
                j++;

                //Message line = 18
                sw.WriteLine(message.MessageText);
                j++;

                if (inEditMode) {
                    for (int i = j; i < 24; i++) {
                        sw.WriteLine(existingText[i]);
                    }
                } else {
                    for (int i = j; i < 24; i++) {
                        sw.WriteLine();
                        j++;
                    }
                }
                success = true;
            } catch (IOException) {
                success = false;
            }

            sw.Close();

            return success;
        }
        /// <summary>Writes the text message to a file, in Motorola format.</summary>
        /// <param name="message">The message.</param>
        /// <returns>True, if sucessful, False otherwise.</returns>
        private static bool WriteMotorolaMessgeFile(TextMessage message)
        {
            bool success;
            StreamWriter sw = new StreamWriter(message.filePath);

            try {
                //Contact number line = 1
                string number = message.Status == MessageStatus.Recieved ? message.From : message.To;
                sw.WriteLine("Contact: " + number);

                //Date line = 2
                sw.WriteLine("Date: " + message.DateTime.ToShortDateString() + " " + message.DateTime.ToLongTimeString());

                sw.WriteLine();

                //Message line = 4
                sw.WriteLine(message.MessageText);

                success = true;
            } catch (IOException) {
                success = false;
            }

            sw.Close();

            return success;
        }
        /// <summary>Creates a <see cref="TextMessage"/> from a file containing data.</summary>
        /// <param name="format">The message format.</param>
        /// <param name="message">The message to wrap up.</param>
        /// <param name="filePath">The file path.</param>
        /// <returns>A TextMessage containing all relevant information from the file.</returns>
        private static TextMessage CreateTextMessage(MessageFormat format, IMessage message, string filePath)
        {
            MessageStatus textMessageStatus;
            switch (format) {
                case MessageFormat.Nokia: {
                    bool isSentMessage = String.IsNullOrEmpty(message.From) && !String.IsNullOrEmpty(message.To);
                    textMessageStatus = isSentMessage ? MessageStatus.Sent : MessageStatus.Recieved;
                    break;
                }
                case MessageFormat.Motorola: {
                    textMessageStatus = MessageStatus.Recieved; //can't distingish status from data in text file
                    break;
                }
                default:
                    throw new NotImplementedException("Unable to read " + format.ToString() + "...yet!");
            }

            TextMessage result = new TextMessage(format, message.MessageText, message.From, message.To, message.DateTime,
                textMessageStatus,
                filePath);

            return result;
        }
        /// <summary>Writes the text message to a file.</summary>
        /// <param name="existingText">Any existing text, usually read from the file before editing.</param>
        /// <param name="message">The message.</param>
        /// <param name="format">The message format.</param>
        /// <returns>True, if sucessful, False otherwise.</returns>
        public static bool WriteTextMessage(List<string> existingText, TextMessage message, MessageFormat format)
        {
            bool result;

            switch (format) {
                case MessageFormat.Nokia: {
                        result = WriteNokiaMessageFile(existingText, message);
                        break;
                    }
                case MessageFormat.Motorola: {
                        result = WriteMotorolaMessgeFile(message);
                        break;
                    }
                default:
                    result = false;
                    break;
            };

            return result;
        }