using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Resources;
using System.Reflection;
using System.Drawing.Imaging;
using System.Threading;

namespace Cone
{
    public partial class Form1 : Form
    {
        private int viSpeed = 1;
        private bool fDrag = false;
        private Point start_point = new Point(0, 0);
        #region Properties
        private bool draggable = true;
        private string exclude_list = "";
        private clCone clCone1 = null;
        private bool fStart = false;
        public string sCurDir { get; set; }
        private int viI { get; set; }
        public Bitmap bmp { get; set; }
        public string[] srgFiles = null;
        public int viImage = 0;
        public Size screen;
        public int viMoseX = 0;
        public int viMoseY = 0;
        private string sFileName;

        public string ExcludeList
        {
            set
            {
                this.exclude_list = value;
            }
            get
            {
                return this.exclude_list.Trim();
            }
        }

        public bool Draggable
        {
            set
            {
                this.draggable = value;
            }
            get
            {
                return this.draggable;
            }
        }
        #endregion
        public Form1()
        {
            InitializeComponent();
            sCurDir = Application.StartupPath;
        }
        #region Overriden Functions

        protected override void OnControlAdded(ControlEventArgs e)
        {
            if (this.Draggable && (this.ExcludeList.IndexOf(e.Control.Name) == -1))
            {
                e.Control.MouseDown += new MouseEventHandler(Form_MouseDown);
                e.Control.MouseUp += new MouseEventHandler(Form_MouseUp);
                e.Control.MouseMove += new MouseEventHandler(Form_MouseMove);
            }
            base.OnControlAdded(e);
        }
        #endregion
        #region
        private void Form1_Load(object sender, EventArgs e)
        {
            backGrColorToolStripMenuItem.Visible = false;
            speedToolStripMenuItem.Visible = false;
            //tb1.Visible = false;
            //tb2.Visible = false;
            tb3.Visible = false;
            helpToolStripMenuItem.Visible = false;
            
            Screen[] screens = Screen.AllScreens;
            screen.Width = screens[0].WorkingArea.Width;
            screen.Height = screens[0].WorkingArea.Height;

            timer1.Enabled = false;
            this.MouseDown += new MouseEventHandler(Form_MouseDown);
            this.MouseUp += new MouseEventHandler(Form_MouseUp);
            this.MouseMove += new MouseEventHandler(Form_MouseMove);
            timer1.Interval = viSpeed;
            tb2.Text = ((float)(1000 / (float)viSpeed)).ToString("00.0");
            bmp = new Bitmap(Cone.Properties.Resources.Image1);
            pictureBox1.Image = new Bitmap(Cone.Properties.Resources.Image1);



            viI = 0;
            fStart = true;
            timer1.Enabled = true;
        }

        #endregion
        #region Event Handlers
        void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {

                this.fDrag = true;
                this.start_point = new Point(e.X, e.Y);
            }
            else
            {
                this.fDrag = false;
            }
        }
        void Form_MouseUp(object sender, MouseEventArgs e)
        {
            this.fDrag = false;
        }
        void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (this.fDrag)
            {
                Point p1 = new Point(e.X, e.Y);
                Point p2 = this.PointToScreen(p1);
                Point p3 = new Point(p2.X - this.start_point.X,
                p2.Y - this.start_point.Y);
                this.Location = p3;
            }
        }
        #endregion

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            if (fStart)
            {
                viI++;
                if (!Directory.Exists(sCurDir + @"\Images"))
                {

                    Directory.CreateDirectory(sCurDir + @"\Images");
                    if (viI > 3)
                    {
                        fStart = false;
                        timer1.Enabled = false;
                        MessageBox.Show("Не удалось создать директорию " + sCurDir + @"\Images\n Создайте её вручную!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    }
                    return;
                }
                else
                {
                    if (!File.Exists(sCurDir + @"\Images\01start.jpg"))
                    {
                        using (MemoryStream memorystream = new MemoryStream())
                        {

                            bmp.Save(memorystream, ImageFormat.Jpeg);
                            FileStream filestream = new FileStream(sCurDir + @"\Images\01start.jpg", FileMode.OpenOrCreate,
                                 FileAccess.ReadWrite, FileShare.ReadWrite);
                            filestream.Write(memorystream.GetBuffer(), 0, (int)memorystream.Length);
                            //Сохраняем
                            filestream.Flush();
                            //Освобождаем сохраненный файл для других
                            filestream.Close();
                        }
                        if (viI > 5)
                        {
                            MessageBox.Show("Не удалось создать стартовый файл " + sCurDir + @"\Images\01start.jpg\n Создайте его вручную, или сохраните файл под именем  01start.jpg через меню File п. Add Image", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            fStart = false;
                            timer1.Enabled = false;
                        }
                        return;

                    }
                    else
                    {

                        fStart = false;
                        vGetFiles();
                        clCone1 = new clCone(this);
                        clCone1.vNewSize();
                        return;
                    }


                }

            }


            if (clCone1 != null)
            {
                clCone1.LineTick();
            }
        }
        #region vGetFiles
        private void vGetFiles()
        {
            string s = string.Empty;
            string s1 = ".jpg;.jpeg;.png;.bmp";
            int viI = 0;
            string[] files = Directory.GetFiles(sCurDir + @"\Images", "*.*");
            foreach (string str in files)
            {
                s = files[viI].ToString().Trim().ToLower();
                s = Path.GetExtension(s);
                if (s1.Contains(s))
                {
                    viI++;
                }
            }
            if (viI > 0)
            {

                srgFiles = new string[viI];
                viI = 0;
                foreach (string str in files)
                {
                    s = str[viI].ToString().Trim().ToLower();
                    s = Path.GetExtension(s);
                    if (s1.Contains(s))
                    {
                        s = files[viI].ToString().Trim().ToLower();
                        srgFiles[viI] = s;
                        viI++;
                    }
                }
            }
        }
        #endregion

        #region Изменился размер
        private void pictureBox1_ClientSizeChanged(object sender, EventArgs e)
        {
            if (clCone1 != null)
            {
                clCone1.vNewSize();
            }
        }
        #endregion

        private void imageToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            viMoseX = e.X;
            viMoseY = e.Y;
        }

        private void addImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            string s = string.Empty;
            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.Filter = "All Images Files|*.bmp;*.jpeg;*.jpg;*.png" +
                "|Windows Bitmap (*.bmp)|*.bmp" +
                "|JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg" +
                "|Portable Network Graphics (*.png)|*.png";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {

                sFileName = openFileDialog1.FileName;

            }
            else
            {
                timer1.Enabled = true;
                return;

            }
            if (MessageBox.Show("Сохранить файл " + sFileName, "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
            {
                timer1.Enabled = true;
                return;

            }
            Bitmap bmpTmp;
            Bitmap bmpTmp1;
            double d1, d2,d3;
            try
            {
                bmpTmp1 = new Bitmap(sFileName);

                if (bmpTmp1.Width > 1000 || bmpTmp1.Height > 800)
                {
                    if (MessageBox.Show("Файл  имеет размеры более 1000*800, что не рекомендуется в учебной программе! \n Уменьшить!", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        d1 = (double)bmpTmp1.Width / (double)1000;
                        d2 = (double)bmpTmp1.Height / (double)800;
                        if (d1 >= d2)
                        {
                            d3 = d1;
                        }
                        else
                        {
                            d3 = d2;
                        }
                        bmpTmp = new Bitmap((int)((double)bmpTmp1.Width / (double)d3), (int)((double)bmpTmp1.Height / (double)d3));
                        Graphics gr = Graphics.FromImage(bmpTmp);
                        Rectangle destRect = new Rectangle(0, 0, bmpTmp.Width, bmpTmp.Height);
                        Rectangle srcRect = new Rectangle(0, 0, bmpTmp1.Width, bmpTmp1.Height);
                        gr.DrawImage(bmpTmp1, destRect, srcRect, GraphicsUnit.Pixel);
                        gr.Dispose();

                    }
                    else
                    {
                        bmpTmp1.Dispose();
                        bmpTmp = new Bitmap(sFileName);
                    }

                }
                else
                {
                    bmpTmp1.Dispose();
                    bmpTmp = new Bitmap(sFileName);
                }



            }
            catch (Exception)
            {
                MessageBox.Show("Не удалось преобразоватиь файл " + sFileName, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                timer1.Enabled = true;
                return;
            }
            if (MessageBox.Show("Введите имя файла без расширения, расширение будет взято из имени сохраняемого файла! ", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
            {
                timer1.Enabled = true;
                return;
            }

            saveFileDialog1.InitialDirectory = sCurDir + @"\Images";

            saveFileDialog1.Filter = "All Images Files|*.bmp;*.jpeg;*.jpg;*.png" +
               "|Windows Bitmap (*.bmp)|*.bmp" +
               "|JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg" +
               "|Portable Network Graphics (*.png)|*.png";





            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                
                MemoryStream memorystream = new MemoryStream();
                string s1 = Path.GetExtension(saveFileDialog1.FileName).ToLower();
                FileStream filestream;
                switch (s1)
                {
                    case ".bmp":
                        bmpTmp.Save(memorystream, ImageFormat.Bmp);

                        break;
                    case ".jpg":
                    case ".jpeg":
                        bmpTmp.Save(memorystream, ImageFormat.Jpeg);
                        break;
                    case ".png":
                        bmpTmp.Save(memorystream, ImageFormat.Png);
                        break;

                }


                filestream = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                filestream.Write(memorystream.GetBuffer(), 0, (int)memorystream.Length);
                //Сохраняем
                filestream.Flush();
                //Освобождаем сохраненный файл для других
                filestream.Close();
                bmpTmp.Dispose();

            }
            vGetFiles();
            timer1.Enabled = true;
        }
        #region About
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 ab = new AboutBox1();
            ab.Show();
        }
        #endregion


        #region speed
        private void Bigger_Click(object sender, EventArgs e)
        {
            vBigger();
        }
        private void vBigger()
        {
            if (viSpeed > 1)
            {
                if (viSpeed < 10)
                {
                    viSpeed -= 1;
                }
                else
                {
                    if (viSpeed <= 100)
                    {
                        viSpeed -= 5;
                    }
                    else
                    {
                        viSpeed -= 10;

                    }
                }
            }

            tb2.Text = ((float)(1000 / (float)viSpeed)).ToString("00.0");
            timer1.Interval = viSpeed;

        }

        private void Smaller_Click(object sender, EventArgs e)
        {
            vSmaller();
        }

        private void vSmaller()
        {
            if (viSpeed < 200)
            {
                if (viSpeed < 10)
                {
                    viSpeed += 1;
                }
                else
                {
                    if (viSpeed <= 100)
                    {
                        viSpeed += 5;
                    }
                    else
                    {
                        viSpeed += 10;

                    }
                }
                if (viSpeed > 200) viSpeed = 200;
            }
            tb2.Text = ((float)(1000 / (float)viSpeed)).ToString("00.0");
            timer1.Interval = viSpeed;

        }

        #endregion

        #region Image Forvard
        private void imagToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (srgFiles != null && srgFiles.Length > viImage)
            {
                viImage++;
                if (viImage >= srgFiles.Length)
                {
                    viImage = 0;
                }

            }
            if (clCone1 != null)
            {
                clCone1 = new clCone(this);
                clCone1.vNewSize();
            }
        }

        #endregion

        #region Image back 
        private void changeImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (srgFiles != null && srgFiles.Length >= 0)
            {
                viImage--;
                if (viImage <  0)
                {
                    viImage = srgFiles.Length-1;
                }

            }
            if (clCone1 != null)
            {
                clCone1 = new clCone(this);
                clCone1.vNewSize();
            }
        }
        #endregion

        private void deleteImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            string s = string.Empty;
            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.Filter = "All Images Files|*.bmp;*.jpeg;*.jpg;*.png" +
                "|Windows Bitmap (*.bmp)|*.bmp" +
                "|JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg" +
                "|Portable Network Graphics (*.png)|*.png";
            openFileDialog1.InitialDirectory = sCurDir + @"\Images";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {

                sFileName = openFileDialog1.FileName;
                File.Delete(sFileName);
                Thread.Sleep(500);
                if (File.Exists(sFileName))
                {
                    MessageBox.Show("Не удалось удалить файл " + sFileName + "\n Попробуйте удалить его другим способом!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Файл удалён " + sFileName + " !", "Information!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }


                vGetFiles();

                timer1.Enabled = true;
                

            }
            else
            {
                timer1.Enabled = true;
            }

        }

        

       

    }
}

