using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace StekloMaster
{
    public partial class ИЗОБРАЖЕНИЯ_главная : Form
    {
        public ИЗОБРАЖЕНИЯ_главная()
        {
            InitializeComponent();
        }
        string putin = "";
        bool passworddeletete = true;

        private void ИЗОБРАЖЕНИЯ_главная_Shown(object sender, EventArgs e)
        {
            if (Application.StartupPath.IndexOf("comp") != -1)
            {
                putin = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf("\\comp"));
            }
            else
            {
                putin = Application.StartupPath;
            }

            var lst = new ImageList();
            lst.Images.Add(Properties.Resources.open_file_button);
            lst.Images.Add(Properties.Resources.picture_frame);
            lst.Images.Add(Properties.Resources.close);
           
            label1.Text = putin + "\\Галерея";
            label2.Text = putin + "\\Превью_галерея";
            loadlist();
            metroTextBox1.Focus();
        }


        void loadlist()
        {
            listView1.Clear();

            forlders = new List<string>(Directory.EnumerateDirectories(label1.Text));
            files = new List<string>(Directory.EnumerateFiles(label1.Text));

            int count = forlders.Count + files.Count;

            images = new ImageList();
            images.ImageSize = new Size(128, 128);
            images.ColorDepth = ColorDepth.Depth32Bit;
            images.Images.Add("Directory", Properties.Resources.file_folder__1_);
            images.Images.Add("Directory", Properties.Resources.download_file);

            listView1.LargeImageList = images;
            cache = null;
            cIdx = 0;
            listView1.VirtualListSize = count;
        }
      

        private void button1_Click(object sender, EventArgs e)
        {
            if (label1.Text != "Поиск")
                loadlist();
            else
                metroButton6_Click(null, null);
        }

        private void file_Click(object sender, EventArgs e)
        {
            string msg = "";
            if (label1.Text == "Поиск")
            {
                string puts = Path.GetTempPath() + "\\" + videlen.Replace(".fkv", "");
                Shifr.DecryptFiless(videlentag, puts, "qF29s4JE", out msg);
                System.Diagnostics.Process.Start(puts);
            }
            else
            {
                string puts = Path.GetTempPath() + "\\" + videlen.Replace(".fkv", "");
                Shifr.DecryptFiless(label1.Text + "\\" + videlen, puts, "qF29s4JE", out msg);
                System.Diagnostics.Process.Start(puts);
            }
        }

        private void image_Click(object sender, EventArgs e)
        {
            ИЗОБРАЖЕНИЯ_просмотр f1 = new ИЗОБРАЖЕНИЯ_просмотр();
            f1.Owner = this;
            if (label1.Text == "Поиск")
            {
                f1.image = videlentag;
            }
            else
            {
                f1.folder = label1.Text;
                f1.image = label1.Text + "\\" + videlen;
            }
            f1.Show();
            f1.Focus();
        }

        private void image_delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Вы действительно хотите удалить файл?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {

                if (label1.Text == "Поиск")
                {
                    if (File.Exists(videlentag))
                        File.Delete(videlentag);
                    if (File.Exists(videlentag.Replace(putin + "\\Галерея", putin + "\\Превью_галерея")))
                        File.Delete(videlentag.Replace(putin + "\\Галерея", putin + "\\Превью_галерея"));
                    metroButton6_Click(null, null);
                }
                else
                {
                    if (File.Exists(label1.Text + "\\" + videlen))
                        File.Delete(label1.Text + "\\" + videlen);
                    if (File.Exists(label2.Text + "\\" + videlen))
                        File.Delete(label2.Text + "\\" + videlen);
                    loadlist();
                }
            }
            
        }

        private void folder_deletf_Click(object sender, EventArgs e)
        {
            ИЗОБРАЖЕНИЯ_пароль f1 = new ИЗОБРАЖЕНИЯ_пароль();
            f1.Owner = this;
            f1.Show();
            f1.putfolder = label1.Text + "\\" + videlen;
            f1.putminifolder = label2.Text + "\\" + videlen;
            f1.passworddeletete = passworddeletete;
            f1.Focus();
            /*if (MessageBox.Show("Вы действительно хотите удалить папку?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                if (Directory.Exists(label2.Text + "\\" + videlen))
                    Directory.Delete(label2.Text + "\\" + videlen, true);
                if (Directory.Exists(label1.Text + "\\" + videlen))
                    Directory.Delete(label1.Text + "\\" + videlen, true);
                string put = label1.Text.Replace(putin + "\\", "");
                loadlist();
            }*/
        }

        private void folder_delete_Click(object sender, EventArgs e)
        {
            //нет папок при поиске
            string[] file = Directory.GetFiles(label1.Text + "\\" + videlen);
            string[] pap = Directory.GetDirectories(label1.Text + "\\" + videlen);
            if (file.Length == 0 && pap.Length == 0)
            {
                if (MessageBox.Show("Вы действительно хотите удалить папку?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    if(Directory.Exists(label2.Text + "\\" + videlen))
                        Directory.Delete(label2.Text + "\\" + videlen,true);
                    if (Directory.Exists(label1.Text + "\\" + videlen))
                        Directory.Delete(label1.Text + "\\" + videlen, true);
                    loadlist();
                }
            }
            else
            {
                MessageBox.Show("В удаляемой папке существуют другие файлы или папки!");
            }
        }

        private void folder_Click(object sender, EventArgs e)
        { 
            label1.Text = label1.Text + "\\" + videlen;
            label2.Text = label2.Text + "\\" + videlen;
            loadlist();
        }

        private void acsport_click(object sender, EventArgs e)
        {

            using (var dialog = new SaveFileDialog())
            {
                dialog.FileName = videlen.Replace(".akv", "").Replace(".fkv", "");
                dialog.Filter = "Все файлы(*.*)|*.*";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string msg = "";
                    string putfile = "";
                    if (label1.Text == "Поиск")
                    {
                        putfile = videlentag;
                    }
                    else
                    {
                        putfile = label1.Text + "\\" + videlen;
                    }
                    Shifr.DecryptFiless(putfile, dialog.FileName, "qF29s4JE", out msg);
                }
            }
        }

        string videlen = "";
        string videlentag = "";
        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ContextMenuStrip m = new ContextMenuStrip();
                ListViewItem currentMouseOverRow = listView1.HitTest(e.X, e.Y).Item;
                if (currentMouseOverRow != null)
                {
                    var item = new ToolStripMenuItem("Просмотреть");
                    item.Image = Properties.Resources.eye_see_observe;
                    videlen = currentMouseOverRow.Text;
                    if (label1.Text == "Поиск")
                    {
                        videlentag = currentMouseOverRow.Tag.ToString();
                    }
                    if (currentMouseOverRow.ImageIndex == 0)
                    {
                        item.Click += folder_Click;

                    }
                    else if(currentMouseOverRow.ImageIndex == 1)
                    {
                        item.Click += file_Click;
                        m.Items.Add(item);
                        item = new ToolStripMenuItem("Экспортировать");
                        item.Image = Properties.Resources.export;
                        item.Click += acsport_click;
                    }
                    else
                    {
                        item.Click += image_Click;
                        m.Items.Add(item);
                        item = new ToolStripMenuItem("Экспортировать");
                        item.Image = Properties.Resources.export;
                        item.Click += acsport_click;
                    }
                    m.Items.Add(item);

                    item = new ToolStripMenuItem("Удалить");
                    item.Image = Properties.Resources.delete_cross;
                    if (currentMouseOverRow.ImageIndex == 0)
                    {
                        item.Click += folder_delete_Click;
                        m.Items.Add(item);
                        item = new ToolStripMenuItem("Удалить с вложениями");
                        item.Image = Properties.Resources.delete_cross;
                        item.Click += folder_deletf_Click;
                    }
                    else
                    {
                        item.Click += image_delete_Click;
                    }
                    m.Items.Add(item);
                   
                }
                m.Show(listView1, new Point(e.X, e.Y));

            }
        }

        private void metroButton5_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "ИЗОБРАЖЕНИЯ_добавить")
                {
                    MessageBox.Show("Добавление файлов уже открыто!");
                    return;
                }
            }
            ИЗОБРАЖЕНИЯ_добавить f1 = new ИЗОБРАЖЕНИЯ_добавить();
            f1.Owner = this;
            if (label1.Text != "Поиск")
            {
                f1.put_to_papka = label1.Text;
                f1.put_to_preview = label2.Text;
            }
            else
            {
                f1.put_to_papka =  putin + "\\Галерея";
                f1.put_to_preview = putin + "\\Превью_галерея";
            }
            f1.Show();
            f1.Focus();
        }


        List<string> forlders;
        List<string> files;
        ImageList images;
        
        public void obnovlen_tek()
        {
            try
            {
                loadlist();
            }
            catch { }
        }
        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem currentMouseOverRow = listView1.HitTest(e.X, e.Y).Item;
            if (currentMouseOverRow != null)
            {
               if (currentMouseOverRow.ImageIndex == 0)
                {
                    //двигаем treeview
                    label1.Text = label1.Text + "\\" + currentMouseOverRow.Text;
                    label2.Text = label2.Text + "\\" + currentMouseOverRow.Text;
                    loadlist();
                }
                else if (currentMouseOverRow.ImageIndex == 1)
                {
                    string msg = "";
                    string puts = Path.GetTempPath() + "\\" + currentMouseOverRow.Text.Replace(".fkv", "");
                    if (label1.Text == "Поиск")
                    {
                        Shifr.DecryptFiless(currentMouseOverRow.Tag.ToString(), puts, "qF29s4JE", out msg);
                    }
                    else
                    {
                        Shifr.DecryptFiless(label1.Text + "\\" + currentMouseOverRow.Text, puts, "qF29s4JE", out msg);
                    }
                    System.Diagnostics.Process.Start(puts);
                }
                else
                {

                    ИЗОБРАЖЕНИЯ_просмотр f1 = new ИЗОБРАЖЕНИЯ_просмотр();
                    f1.Owner = this;
                    if (label1.Text == "Поиск")
                    {
                        f1.image = currentMouseOverRow.Tag.ToString();
                    }
                    else
                    {
                        f1.folder = label1.Text;
                        f1.image = label1.Text + "\\" + currentMouseOverRow.Text;
                    }
                    f1.Show();
                    f1.Focus();
                }
            }
        }

        private void metroButton1_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "ИЗОБРАЖЕНИЯ_добавить_папку")
                {
                    MessageBox.Show("Создание новой папки уже открыто!");
                    return;
                }
            }
            ИЗОБРАЖЕНИЯ_добавить_папку f1 = new ИЗОБРАЖЕНИЯ_добавить_папку();
            f1.Owner = this;
            f1.Show();
            f1.put = label1.Text;
            f1.putPr = label2.Text;
            f1.Focus();
        }
        

        private ListViewItem[] cache;
        private int cIdx; // Index of the first item in cache

        private ListViewItem LogToListItem(int ItemIndex)
        {
            ListViewItem item = null;
            int index = 0;
            if(label1.Text == "Поиск")
            {
                index = ItemIndex;
                if (files[index].IndexOf(".akv") != -1)
                {
                    string filenam = files[index].Substring(files[index].LastIndexOf("\\") + 1);
                    item = new ListViewItem(filenam);
                    try
                    {
                        Image img;
                        using (var bmpTemp = new Bitmap(files[index].Replace(putin + "\\Галерея", putin + "\\Превью_галерея")))
                        {
                            img = new Bitmap(bmpTemp);
                        }
                        images.Images.Add(img);
                        item.ImageIndex = images.Images.Count - 1;
                        item.Tag = files[index];
                    }
                    catch { }
                }
                else
                {
                    item = new ListViewItem(files[index].Substring(files[index].LastIndexOf("\\") + 1), 1);
                    item.Tag = files[index];
                }
            }
            else if (ItemIndex > forlders.Count - 1)
            {
                index = ItemIndex - forlders.Count;
                if (files[index].IndexOf(".akv") != -1)
                {
                    string filenam = files[index].Substring(files[index].LastIndexOf("\\") + 1);
                    item = new ListViewItem(filenam);
                    try
                    {
                        Image img;
                        using (var bmpTemp = new Bitmap(label2.Text + "\\" + filenam))
                        {
                            img = new Bitmap(bmpTemp);
                        }
                        images.Images.Add(img);
                        item.ImageIndex = images.Images.Count - 1;
                    }
                    catch { }
                }
                else
                {
                    item = new ListViewItem(files[index].Substring(files[index].LastIndexOf("\\") + 1), 1);
                }
            }
            else
            {
                //дирректория
                index = ItemIndex;
                item = new ListViewItem(forlders[index].Substring(forlders[index].LastIndexOf("\\") + 1), 0);
            }
            return item;
        }


        private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            if (cache != null && e.ItemIndex >= cIdx && e.ItemIndex < cIdx + cache.Length)
            {
                // Cache hit
                e.Item = cache[e.ItemIndex - cIdx];
            }
            else
            {
                // Cache miss
                e.Item = LogToListItem(e.ItemIndex);
            }
        }

        private void listView1_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
        {
            if (cache != null && e.StartIndex >= cIdx && e.EndIndex <= cIdx + cache.Length)
            {
                // No need to rebuild the cache now
                return;
            }

            cIdx = e.StartIndex;
            int length = e.EndIndex - e.StartIndex + 1;
            cache = new ListViewItem[length];

            // Fill the cache
            for (int i = 0; i < length; i++)
                cache[i] = LogToListItem(e.StartIndex + i);
        }

        private void metroButton4_Click(object sender, EventArgs e)
        {
            label1.Text = putin + "\\Галерея";
            label2.Text = putin + "\\Превью_галерея";
            loadlist();
        }

        private void metroButton3_Click(object sender, EventArgs e)
        {
            if (label1.Text != putin + "\\Галерея")
            {
                if (label1.Text == "Поиск")
                {
                    label1.Text = putin + "\\Галерея";
                    label2.Text = putin + "\\Превью_галерея";
                }
                else
                {
                    label1.Text = label1.Text.Substring(0, label1.Text.LastIndexOf("\\"));
                    label2.Text = label2.Text.Substring(0, label2.Text.LastIndexOf("\\"));
                }
            }
            loadlist();
        }

        private void metroButton6_Click(object sender, EventArgs e)
        {
            if(metroTextBox1.Text != "")
            {
                label1.Text = "Поиск";
                files = new List<string>(Directory.EnumerateFiles(putin + "\\Галерея", "*"+metroTextBox1.Text+"*.*", SearchOption.AllDirectories));

                int count = files.Count;

                images = new ImageList();
                images.ImageSize = new Size(128, 128);
                images.ColorDepth = ColorDepth.Depth32Bit;
                images.Images.Add("Directory", Properties.Resources.file_folder__1_);
                images.Images.Add("Directory", Properties.Resources.download_file);
                listView1.LargeImageList = images;
                cache = null;
                cIdx = 0;
                listView1.VirtualListSize = count;
            }
        }

        private void metroTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                metroButton6_Click(null, null);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            passworddeletete = true;
        }

        public void correctpass()
        {
            passworddeletete = false;
            timer1.Start();
        }
    }
}
