using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Windows.Forms;

namespace StarEngine
{
    internal partial class CrashReportDialog : Form
    {
        public CrashReportDialog()
            : this(null)
        {
        }

        public CrashReportDialog(Exception e)
        {
            this.InitializeComponent();
            this.Exception = e;
        }

        public Exception Exception
        {
            get { return this.exception; }
            set
            {
                this.exception = value;

                Version version = Assembly.GetExecutingAssembly().GetName().Version;

                List<string> lines = new List<string>();
                lines.Add("Version: " + version.ToString());
                lines.Add("");
                lines.Add(value.GetType().Name);
                lines.Add("");
                lines.Add(value.Message);
                lines.Add("");
                lines.Add(value.StackTrace);

                this.ExceptionDescriptionTextBox.Lines = lines.ToArray();
            }
        }
        private Exception exception;

        private void CloseButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SendMailLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.SendMail();
        }

        private void MailIconPictureBox_Click(object sender, EventArgs e)
        {
            this.SendMail();
        }

        private void SendMail()
        {
            string to = "star@users.sourceforge.jp";
            string subject = "Star Engine Crash Report";
            string body = "(発生状況など、なんでもご記入ください。)" + Environment.NewLine +
                "" + Environment.NewLine +
                "" + Environment.NewLine +
                "エラーの詳細:" + Environment.NewLine +
                "" + Environment.NewLine +
                this.ExceptionDescriptionTextBox.Text;
            string process = string.Format("mailto:{0}?subject={1}&body={2}",
                this.UrlEncodeForMail(to),
                this.UrlEncodeForMail(subject),
                this.UrlEncodeForMail(body));
            if (1000 < process.Length)
                process = process.Substring(0, 1000);
            Process.Start(process);
        }

        private string UrlEncodeForMail(string str)
        {
            string result = str.Replace("%", "%25").Replace("\r", "%0D").Replace("\n", "%0A").Replace("&", "%26")
                .Replace("=", "%3D").Replace("?", "%3F").Replace(",", "%2C");
            return result;
        }
    }
}