using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Gecko;
using System.Threading;
using System.Net;
using System.Diagnostics;
using Noesis.Javascript;

namespace Sownloader
{
    public partial class Sownloader : Form
    {
        private bool showList = false, isDownloading = false;
        Thread downloadThread;

        FileHandler.INIClass inifile;
        FileHandler.Logfile logfile;
        public Sownloader()
        {
            InitializeComponent();
            Xpcom.Initialize("Firefox");
 
            panelFooter.Visible = false;
            inifile = new FileHandler.INIClass();
            logfile = new FileHandler.Logfile();
 
        }
        #region ToolStrip 
        /// <summary>
        /// The refresh button. Handels the button and the menuStripItem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            geckoBrowser.Reload();
        }
        /// <summary>
        /// The back button. Handels the button and the menuStripItem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBack_Click(object sender, EventArgs e)
        {
            geckoBrowser.GoBack();
        }
        /// <summary>
        /// The forward button. Handels the button and the menuStripItem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnForward_Click(object sender, EventArgs e)
        {
            geckoBrowser.GoForward();
        }
        /// <summary>
        /// The go button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGo_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate(tbNavigate.Text);
        }
        /// <summary>
        /// The add button. Also handles the MenuStripItem.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if(Directory.Exists(inifile.SAVEPATH))
            {
                saveMediaFileDialog.InitialDirectory = inifile.SAVEPATH;
            }
            saveMediaFileDialog.ShowDialog();
        }
        #endregion
        #region GeckoWebbrowser
        private void geckoBrowser_DocumentCompleted(object sender, Gecko.Events.GeckoDocumentCompletedEventArgs e)
        {

            string sourcecode = "";
            GeckoHtmlElement element = null;
            var geckoDomElement = geckoBrowser.Document.DocumentElement;
            if (geckoDomElement is GeckoHtmlElement)
            {
                element = (GeckoHtmlElement)geckoDomElement;
                var innerHtml = element.InnerHtml;
                sourcecode = innerHtml;
            }

            try
            {
                string encodedURL = "";

                // Performance DATA
                string RegexPattern = "\"performance\":{(?<performanceDATA>.*?),\"performed_by\"";
                Regex rgx = new Regex(RegexPattern);
                Match RegexMatch = rgx.Match(sourcecode);
                sourcecode = RegexMatch.Groups["performanceDATA"].Value;

                // Audio
                RegexPattern = "media_url\":\"(?<audioURL>.*?)\"";
                rgx = new Regex(RegexPattern);
                RegexMatch = rgx.Match(sourcecode);
                encodedURL = RegexMatch.Groups["audioURL"].Value;

                // Video
                RegexPattern = "video_media_mp4_url\":\"(?<videoURL>.*?)\"";
                rgx = new Regex(RegexPattern);
                RegexMatch = rgx.Match(sourcecode);

                if (!string.IsNullOrEmpty(RegexMatch.Groups["videoURL"].Value))
                    encodedURL = RegexMatch.Groups["videoURL"].Value;

                tbMediaURL.Text = DecodeSmuleURL(encodedURL);

            }
            catch (Exception)
            {

                throw;
            }

            btnRefresh.Image = Properties.Resources.icon_refresh;

            if (geckoBrowser.CanGoBack)
            {
                btnBack.Enabled = true;
                backwardToolStripMenuItem.Enabled = true;
            }
            else
            {
                btnBack.Enabled = false;
                backwardToolStripMenuItem.Enabled = false;
            }

            if (geckoBrowser.CanGoForward)
            {
                btnForward.Enabled = true;
                forwardToolStripMenuItem.Enabled = true;
            }
            else
            {
                btnForward.Enabled = false;
                forwardToolStripMenuItem.Enabled = false;
            }
        }

        private void geckoBrowser_Navigating(object sender, Gecko.Events.GeckoNavigatingEventArgs e)
        {
            btnRefresh.Image = Properties.Resources.icon_refresh_ajax;
            tbNavigate.Text = e.Uri.ToString();
        }

        private void geckoBrowser_Navigated(object sender, GeckoNavigatedEventArgs e)
        {
            tbNavigate.Text = geckoBrowser.Url.AbsoluteUri;
        }
        #endregion
        #region Menu
        private void copyMediaURLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(tbMediaURL.Text);
            System.Media.SystemSounds.Asterisk.Play();
        }

        private void showListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (showList)
            {
                showList = false;
                panelList.Visible = false;
            }
            else
            {
                showList = true;
                panelList.Visible = true;
            }
        }
        private void eToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void tagEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TagEditor te = new TagEditor();
            te.Location = new Point(this.Location.X + (int)(this.Width / 2) - (int)(te.Width / 2), this.Location.Y + (int)(this.Height / 2) - (int)(te.Height / 2));
            te.Show();
        }

        private void converterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Converter cvt = new Converter();
            cvt.Location = new Point(this.Location.X + (int)(this.Width / 2) - (int)(cvt.Width / 2), this.Location.Y + (int)(this.Height / 2) - (int)(cvt.Height / 2));
            cvt.Show();
        }

        private void newsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("https://www.sownloader.com/news");
        }

        private void marvinKleinMusicFavouritesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("https://www.sownloader.com/marvinkleinmusic-favourites.php?view=swn");
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings stg = new Settings();
            stg.Location = new Point(this.Location.X + (int)(this.Width / 2) - (int)(stg.Width / 2), this.Location.Y + (int)(this.Height / 2) - (int)(stg.Height / 2));
            if(stg.ShowDialog() == DialogResult.OK)
            {
                // Reload the ini
                inifile = new FileHandler.INIClass();
                // Reload some settings
                this.TopMost = inifile.KEEPFOCUSED;
            }
        }

        private void smuleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("https://www.smule.com");
        }

        private void yokeeKaraokeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("https://www.yokee.tv");
        }

        private void smuleLoginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("https://www.smule.com/user/login");
        }

        private void helpToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("https://www.sownloader.com/help");
        }

        private void websiteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("https://www.sownloader.com/");
        }

        private void searchForUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateSearch updatesearch = new UpdateSearch(true);
            updatesearch.SearchForUpdate();
        }

        private void devConsoleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebConsole console_frm = new WebConsole();
            console_frm.Location = new Point(this.Location.X + (int)(this.Width / 2) - (int)(console_frm.Width / 2), this.Location.Y + (int)(this.Height / 2) - (int)(console_frm.Height / 2));
            console_frm.Show();
        }

        private void licensesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Licenses lcs = new Licenses();
            lcs.Location = new Point(this.Location.X + (int)(this.Width / 2) - (int)(lcs.Width / 2), this.Location.Y + (int)(this.Height / 2) - (int)(lcs.Height / 2));
            lcs.Show();
        }

        private void sendFeedbackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("mailto:support@sownloader.com");
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void aboutSownloader8ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            geckoBrowser.Navigate("http://sownloader.com/news/2018/04/06/introducing-sownloader-8/");
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About abt = new About();
            abt.Location = new Point(this.Location.X + (int)(this.Width / 2) - (int)(abt.Width / 2), this.Location.Y + (int)(this.Height / 2) - (int)(abt.Height / 2));
            abt.ShowDialog();
        }
        private void donateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=M3PZRJBBPN2GJ");
        }
        #endregion
        #region Download-Related
        private void tbMediaURL_TextChanged(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(tbMediaURL.Text))
            {
                copyMediaURLToolStripMenuItem.Enabled = false;
                btnAdd.Enabled = false;
                btnDownload.Enabled = false;
                addToolStripMenuItem.Enabled = false;
            }
            else
            {
                copyMediaURLToolStripMenuItem.Enabled = true;
                btnAdd.Enabled = true;
                addToolStripMenuItem.Enabled = true;
                btnDownload.Enabled = true;
                switch (Path.GetExtension(tbMediaURL.Text))
                {
                    case ".m4a":
                        saveMediaFileDialog.Filter = "MP4 Audio (*.m4a)|*.m4a|MP3 Audio (*.mp3)|*.mp3";
                        saveMediaFileDialog.DefaultExt = ".m4a";
                        break;
                    case ".mp4":
                        saveMediaFileDialog.Filter = "MP4 Video (*.mp4)|*.mp4|MP4 Audio (*.m4a)|*.m4a";
                        saveMediaFileDialog.DefaultExt = ".mp4";
                        break;
                    default:
                        break;
                }
            }
        }

        private void saveMediaFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            string OriginalExtension = Path.GetExtension(tbMediaURL.Text);
            string RequestesExtension = Path.GetExtension(saveMediaFileDialog.FileName);
            string TempFile = Path.Combine(Path.GetTempPath(), Hilfsklassen.GenerateRandomString(5) + OriginalExtension); // Example: C:\Users\Marvin Klein\AppData\Local\Temp\khrww.m4a/.mp4
            string CoverURL = "";
            string CoverPath = "";

            // Search cover art
            try
            {
                // Fetch website sourcecode
                string sourcecode = "";
                GeckoHtmlElement element = null;
                var geckoDomElement = geckoBrowser.Document.DocumentElement;
                if (geckoDomElement is GeckoHtmlElement)
                {
                    element = (GeckoHtmlElement)geckoDomElement;
                    var innerHtml = element.InnerHtml;
                    sourcecode = innerHtml;
                }

                // "cover_url":"https://c-sf.smule.com/sf/s36/arr/05/23/61fe11c3-9bde-4fc9-b1a1-8f3939993909.jpg",
                string RegexPattern = "cover_url\":\"(?<CoverURL>.*?)\"";
                Regex rgx = new Regex(RegexPattern);
                Match RegexMatch = rgx.Match(sourcecode);

                CoverURL = RegexMatch.Groups["CoverURL"].Value;

                // Check whether Cover URL is a valid URI
                if (CoverURL.Substring(0, 5) != "https" && CoverURL.Substring(0, 5) != "http:")
                    CoverURL = "https:" + CoverURL;

                CoverPath = Path.Combine(Application.StartupPath, "covers", Hilfsklassen.GenerateRandomString(5) + Path.GetExtension(CoverURL));

            }
            catch (Exception)
            {
                // No cover art was found
            }

            ListViewItem addListViewItem = lvDownloads.Items.Add(tbMediaURL.Text); // Media URL
            addListViewItem.SubItems.Add(TempFile); // File in temp
            addListViewItem.SubItems.Add(saveMediaFileDialog.FileName); // Users path
            addListViewItem.SubItems.Add(CoverURL); // Cover URL
            addListViewItem.SubItems.Add(CoverPath); // Cover Path
            // ID3Tags
            bool insertBlankTags = true;
            if (inifile.SHOWID3WINDOW)
            {
                ID3Tags id3tags = new ID3Tags();
                id3tags.Location = new Point(this.Location.X + (int)(this.Width / 2) - (int)(id3tags.Width / 2), this.Location.Y + (int)(this.Height / 2) - (int)(id3tags.Height / 2));
                if(id3tags.ShowDialog() == DialogResult.OK)
                {
                    addListViewItem.SubItems.Add(id3tags.TITLE);
                    addListViewItem.SubItems.Add(id3tags.ARTIST);
                    addListViewItem.SubItems.Add(id3tags.APP);
                    addListViewItem.SubItems.Add(id3tags.YEAR);
                    insertBlankTags = false;
                }
                
            }
            // Füge leere Werte ein, wenn das Fenster nicht angezeigt werden soll, oder der Vorgang abgebrochen wird
            if(insertBlankTags)
            {
                addListViewItem.SubItems.Add("");
                addListViewItem.SubItems.Add("");
                addListViewItem.SubItems.Add("");
                addListViewItem.SubItems.Add("");
            }
            lvDownloads.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            EnableDownloadControl();
        }
        /// <summary>
        /// Handles the activation state of the download button
        /// </summary>
        private void EnableDownloadControl()
        {
            btnDownload.Enabled = (lvDownloads.Items.Count > 0) ? true : false;
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            bool directDownload = true;
            if (lvDownloads.Items.Count <= 0)
            {
                directDownload = false;
                if (saveMediaFileDialog.ShowDialog() == DialogResult.OK)
                    directDownload = true;
            }

            if (directDownload)
            {
                isDownloading = true;
                panelFooter.Visible = true;

                btnDownload.Enabled = false;
                btnRemove.Enabled = false;

                downloadThread = new Thread(DownloadFiles);
                downloadThread.Start();
            }
        }
        /// <summary>
        /// Downloads all files from the ListView
        /// </summary>
        private void DownloadFiles()
        {
            int downloadAnzahl = 0;
            lvDownloads.Invoke(new MethodInvoker(delegate ()
            {
                downloadAnzahl = lvDownloads.Items.Count;
            }));

            progressBar1.Invoke(new MethodInvoker(delegate () {
                progressBar1.Maximum = downloadAnzahl;
            }));

            for (int i = 1; i <= downloadAnzahl; i++)
            {
                lblStatus.Invoke(new MethodInvoker(delegate () {
                    lblStatus.Text = "Downloading files... (" + i + "/" + downloadAnzahl + ")";
                }));

                string mediaURL = "", tempFile = "", userPath = "",  coverURL = "", coverPath = "";
                string TITLE = "", ARTIST = "", APP = "", YEAR = "";

                lvDownloads.Invoke(new MethodInvoker(delegate ()
                {
                    mediaURL = lvDownloads.Items[0].SubItems[0].Text;
                    tempFile = lvDownloads.Items[0].SubItems[1].Text;
                    userPath = lvDownloads.Items[0].SubItems[2].Text;
                    coverURL = lvDownloads.Items[0].SubItems[3].Text;
                    coverPath = lvDownloads.Items[0].SubItems[4].Text;
                    TITLE = lvDownloads.Items[0].SubItems[5].Text;
                    ARTIST = lvDownloads.Items[0].SubItems[6].Text;
                    APP = lvDownloads.Items[0].SubItems[7].Text;
                    YEAR = lvDownloads.Items[0].SubItems[8].Text;
                }));

                string inputExtension = Path.GetExtension(mediaURL), outputExtension = Path.GetExtension(userPath);

                logfile.WriteLog("Started download: " + mediaURL + " to " + tempFile, FileHandler.Logfile.LOGLEVEL.INFORMATION);
                HttpWebRequest http = (HttpWebRequest)WebRequest.Create(new Uri(mediaURL));
                http.UserAgent = "Sownloader " + Application.ProductVersion;
                WebResponse response = http.GetResponse();

                try
                {
                    // Create file from stream in temp
                    Stream stream = response.GetResponseStream();
                    using (Stream s = File.Create(tempFile))
                    {
                        stream.CopyTo(s);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to download the file." + Environment.NewLine + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    logfile.WriteLog("Unable to download the file: " + mediaURL + " to " + tempFile + Environment.NewLine + ex.Message, FileHandler.Logfile.LOGLEVEL.ERROR);
                    downloadThread.Abort();
                }

                logfile.WriteLog("Finished download: " + mediaURL + " to " + tempFile, FileHandler.Logfile.LOGLEVEL.INFORMATION);
                // Taglib#
                if (!string.IsNullOrEmpty(coverURL))
                {
                    logfile.WriteLog("Started cover download: " + coverURL + " to " + coverPath, FileHandler.Logfile.LOGLEVEL.INFORMATION);
                    try
                    {
                        HttpWebRequest httpCover = (HttpWebRequest)WebRequest.Create(new Uri(coverURL));
                        http.UserAgent = "Sownloader " + Application.ProductVersion;
                        WebResponse responseCover = httpCover.GetResponse();
                        Stream streamCover = responseCover.GetResponseStream();
                        using (Stream s = File.Create(coverPath))
                        {
                            streamCover.CopyTo(s);
                        }
                        logfile.WriteLog("Cover download has finshed: " + coverURL + " to " + coverPath, FileHandler.Logfile.LOGLEVEL.INFORMATION);
                    }
                    catch (Exception ex)
                    {
                        logfile.WriteLog("Cover download has failed: " + ex.Message, FileHandler.Logfile.LOGLEVEL.ERROR);
                    }    
                }

                // Set ID3Tags
                TagLib.File.LocalFileAbstraction AudioFilePath = new TagLib.File.LocalFileAbstraction(tempFile);
                TagLib.File AudioFile = TagLib.File.Create(AudioFilePath);
                try
                { 
                    AudioFile.Tag.Title = TITLE;
                    AudioFile.Tag.Performers = new string[] { ARTIST };
                    AudioFile.Tag.Album = APP;
                    AudioFile.Tag.Year = Convert.ToUInt32(YEAR);

                    if (File.Exists(coverPath))
                    {
                        AudioFile.Tag.Pictures = new TagLib.Picture[] { new TagLib.Picture(coverPath) };
                        AudioFile.Tag.Pictures[0].Type = TagLib.PictureType.FrontCover;
                    }
                    AudioFile.Save();
                    AudioFile.Dispose();

                }
                catch (Exception ex)
                {
                    logfile.WriteLog("Unable to set ID3Tags for file <" + tempFile + ">" + Environment.NewLine + ex.Message, FileHandler.Logfile.LOGLEVEL.ERROR);
                }

                // Does the file needs to become converted?
                if (inputExtension != outputExtension)
                {
                    // Convert the tempfile in temp to wanted output
                    try
                    {
                        using (Process FFmpeg = new Process())
                        {
                            FFmpeg.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            FFmpeg.StartInfo.FileName = Path.Combine(Application.StartupPath, "ffmpeg.exe");
                            FFmpeg.StartInfo.UseShellExecute = false;
                            FFmpeg.StartInfo.CreateNoWindow = false;

                            string codec = "";

                            switch (outputExtension)
                            {
                                case ".mp3":
                                    codec = "-i " + tempFile + " -f mp3 -b:a " + inifile.BITRATE + " -acodec libmp3lame " + tempFile.Substring(0, tempFile.Length - 4) + ".mp3";
                                    break;
                                case ".m4a":
                                    codec = "-i " + tempFile + " -vn -c:a copy " + tempFile.Substring(0, tempFile.Length - 4) + ".m4a";
                                    break;
                                default:
                                    break;
                            }

                            FFmpeg.StartInfo.Arguments = codec;

                            FFmpeg.Start();

                            while (!FFmpeg.HasExited)
                            {

                            }

                            FFmpeg.Dispose();
                            FFmpeg.Close();

                            File.Delete(tempFile);
                        }

                    }
                    catch (Exception ex)
                    {
                        logfile.WriteLog("Unable to convert files <" + tempFile + "> <output: " + outputExtension + ">" + Environment.NewLine + ex.Message, FileHandler.Logfile.LOGLEVEL.ERROR);
                        throw;
                    }
                }


                File.Copy(tempFile.Substring(0, tempFile.Length - 4) + outputExtension, userPath);
                File.Delete(tempFile);
                lvDownloads.Invoke(new MethodInvoker(delegate ()
                {
                    lvDownloads.Items.RemoveAt(0);
                }));

                progressBar1.Invoke(new MethodInvoker(delegate () {
                    progressBar1.Value = i;
                }));
            }

            this.Invoke(new MethodInvoker(delegate () {
                btnDownload.Enabled = false;
            }));

            isDownloading = false;

            MessageBox.Show("All downloads have finished!", "Downloading has finished!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            panelFooter.Invoke(new MethodInvoker(delegate ()
            {
                panelFooter.Visible = false;
            }));
            downloadThread.Abort();
        }

        private void lvDownloads_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRemove.Enabled = (lvDownloads.SelectedIndices.Count > 0 && !isDownloading) ? true : false;
        }
        #endregion
        /// <summary>
        /// Decodes Smule encrypted URLS
        /// </summary>
        /// <param name="encodedURL"></param>
        /// <returns></returns>
        private string DecodeSmuleURL(string encodedURL)
        {
            string url = "";

            JavascriptContext context = new JavascriptContext();
            context.SetParameter("url", "");
            context.Run(@"function smuleError(e){}

function r(g){var k={},a,l=
0,d,c=0,b,e='',f=String.fromCharCode,h=g.length;for(a=0;64>a;a++)k['ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(a)]=a;for(d=0;d<h;d++)for(a=k[g.charAt(d)],l=(l<<6)+a,c+=6;8<=c;)((b=l>>>(c-=8)&255)||d<h-2)&&(e+=f(b));return e}

s=r('TT18WlV5TXVeLXFXYn1WTF5qSmR9TXYpOHklYlFXWGY+SUZCRGNKPiU0emcyQ2l8dGVsamBkVlpA');

function processRecording(g){if(null===g||'string'!==typeof g||2>g.length||0!==g.indexOf('e:'))return g;for(var k=r(g.substring(2)),a=[],h=0,d,c='',b=0;256>b;b++)a[b]=b;for(b=0;256>b;b++)h=(h+a[b]+s.charCodeAt(b%s.length))%256,d=a[b],a[b]=a[h],a[h]=d;for(var e=h=b=0;e<k.length;e++)b=(b+1)%256,h=(h+a[b])%256,d=a[b],a[b]=a[h],a[h]=d,c+=String.fromCharCode(k.charCodeAt(e)^a[(a[b]+a[h])%256]);0!==c.indexOf('http')&&
smuleError('Failed to decode URL '+g+'; got '+c);return c;}

url = processRecording('" + encodedURL + "');");

            url = context.GetParameter("url").ToString();

            return url;
        }
        private void Sownloader_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.firstStart)
            {
                Properties.Settings.Default.firstStart = false;
                Properties.Settings.Default.Save();
                geckoBrowser.Navigate("http://sownloader.com/news/2018/04/06/introducing-sownloader-8/");
            }
            else
            {
                geckoBrowser.Navigate(inifile.DEFAULTPAGE);
            }
        }

        

        private void Sownloader_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        

        

        
    }
}
