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 Word = Microsoft.Office.Interop.Word;

namespace Moron_s_test
{
    public partial class Form2 : Form
    {
        static int number = 0, n;
        // массив вопросов
        string[] variation = new string[global.n];
        string[] answers = new string[global.n];
        string[,] task = new string[global.k, 4];
        int[,] catRes = new int[global.l, 4];
        string[] answerCatCount = new string[global.l];
        Microsoft.Office.Interop.Word.Application oWord;
        PictureBox[] picture;
        int timeLeft = 5400;
        
        

        public Form2()
        {
            InitializeComponent();
        }


        // Разбивает строку в массив слов
        private string[] arrayWord(string line)
        {
            string[] wordArray = line.Split(new char[] { ' ' });

            return wordArray;
        }
        

        private void Form2_Load(object sender, EventArgs e)
        {
            global.flag = 0;
            number = 0;
            int i = 1, n, l = 0, p, z = 0;
            string path = "";

            button1.Enabled = false;
            string dir = System.IO.Directory.GetCurrentDirectory() + @"\tests\";
            //path = System.IO.Directory.GetCurrentDirectory() + @"\tests\f1_1.html";
            //System.IO.StreamReader file = new System.IO.StreamReader(path);
            //textBox1.Text = file.ReadToEnd();
            //textBox3.Text = path;
            //webBrowser1.Navigate(new Uri(path));

            n = System.IO.Directory.GetFiles(dir, "f*.html", System.IO.SearchOption.TopDirectoryOnly).Count();
            while (System.IO.Directory.GetFiles(dir, "f" + i.ToString() + "*.html", System.IO.SearchOption.TopDirectoryOnly).Count() != 0)
            {
                l++;
                i++;
            }
            string line;
            // Обьявляем файл
            path = System.IO.Directory.GetCurrentDirectory() + @"\tests\conf.txt";
            System.IO.StreamReader filee = new System.IO.StreamReader(path);
            line = filee.ReadLine();
            // Массив для количества вопросов
            answerCatCount = arrayWord(line);

            
            
            Random r = new Random();
            for (p = 0; p < global.l; p++)
            {
                int h = z,m = 0;
                m = 0;
                string[] findFiles = System.IO.Directory.GetFiles(dir, "f" + (p+1).ToString() + "*.html", System.IO.SearchOption.TopDirectoryOnly);
                for (i = 0; i < findFiles.Count(); i++)
                    findFiles[i] = findFiles[i].Replace(dir, "");

                for (i = 0; i < findFiles.Count(); i++)
                {
                    string chubaka;
                    int j, k;
                    j = r.Next(findFiles.Count());
                    k = r.Next(findFiles.Count());
                    if (k != j)
                    {
                        chubaka = findFiles[j];
                        findFiles[j] = findFiles[k];
                        findFiles[k] = chubaka;
                    }
                }

                while (m < Convert.ToInt32(answerCatCount[p]))
                {
                    variation[z + m] = findFiles[m];
                    m++;
                }
                z += Convert.ToInt32(answerCatCount[p]);
            }

            for (i = 0; i < variation.Count(); i++)
            {
                string chubaka;
                int j, k;
                j = r.Next(variation.Count());
                k = r.Next(variation.Count());
                if (k != j)
                {
                    chubaka = variation[j];
                    variation[j] = variation[k];
                    variation[k] = chubaka;
                }
            }

            // Обьявляем файл
            path = System.IO.Directory.GetCurrentDirectory() + @"\tests\key.txt";
            System.IO.StreamReader file = new System.IO.StreamReader(path);

            string[] wordArray;
            int v = 0;
            while ((line = file.ReadLine()) != null)
            {
                int q;
                // Разбиваем строку на массив слов
                wordArray = arrayWord(line);
                for (q = 0; q < wordArray.Count(); q++)
                {
                    task[v, q] = wordArray[q];
                }
                v++;
            }

            global.a = 0;
            for (i = 0; i < task.GetLength(0); i++)
            {
                if (task[i, 1] == "2")
                {
                    task[i, 3] = global.a.ToString();
                    global.a++;
                }
            }
                picture = new PictureBox[global.a];
            for (i = 0; i < picture.Count(); i++)
            {
                picture[i] = new PictureBox();
            }

                //for (i = 0; i < variation.Count(); i++)
                //{
                //    textBox3.Text += variation[i] + "\r\n";
                //}

                path = System.IO.Directory.GetCurrentDirectory() + @"\tests\" + variation[number];
            webBrowser1.Navigate(new Uri(path));
            label1.Text = "Задание(" + (number + 1) + "/" + variation.Count() + "):";
            for (i = 0; i < global.k; i++)
            {
                if (task[i, 0] + ".html" == variation[number])
                {
                    
                    if (task[i, 1] == "0")
                    {
                        label2.Text = "Выберите вариант ответа:";
                        radioButton1.Visible = true;
                        radioButton2.Visible = true;
                        radioButton3.Visible = true;
                        radioButton4.Visible = true;
                        textBox3.Visible = false;
                        pictureBox1.Visible = false;
                        button5.Visible = false;
                        label4.Text = task[i, 3] + " балла(ов)";
                    }
                    else if (task[i, 1] == "1")
                    {
                        label2.Text = "Введите ответ:";
                        radioButton1.Visible = false;
                        radioButton2.Visible = false;
                        radioButton3.Visible = false;
                        radioButton4.Visible = false;
                        textBox3.Visible = true;
                        pictureBox1.Visible = false;
                        button5.Visible = false;
                        label4.Text = task[i, 2] + " балла(ов)";
                    }
                    else if (task[i, 1] == "2")
                    {
                        label2.Text = "Вставьте изображение:";
                        radioButton1.Visible = false;
                        radioButton2.Visible = false;
                        radioButton3.Visible = false;
                        radioButton4.Visible = false;
                        textBox3.Visible = false;
                        pictureBox1.Visible = true;
                        button5.Visible = true;
                        label4.Text = task[i, 2] + " балла(ов)";
                    }
                    break;
                }
            }
            label3.Text = "Оставшееся время: 1:30:00";
            //label4.Text = task[23,2];
        }

        

        private void selector(int a, string[,] task, string[] variat)
        {

            string path;
            int i;
            switch(a)
            {
                    
                case 0:
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "0")
                            {
                                if (radioButton1.Checked) answers[number] = radioButton1.Text;
                                if (radioButton2.Checked) answers[number] = radioButton2.Text;
                                if (radioButton3.Checked) answers[number] = radioButton3.Text;
                                if (radioButton4.Checked) answers[number] = radioButton4.Text;
                            }
                            else if (task[i, 1] == "1")
                                answers[number] = textBox3.Text;
                            else if (task[i, 1] == "2")
                            {
                                picture[Convert.ToInt32(task[i, 3])].Image = pictureBox1.Image;
                            }
                        }
                    }
                    number--;
                    label1.Text = "Задание(" + (number + 1) + "/" + variation.Count() + "):";
                    radioButton1.Checked = false;
                    radioButton2.Checked = false;
                    radioButton3.Checked = false;
                    radioButton4.Checked = false;
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "0")
                            {
                                if (answers[number] == "1") radioButton1.Checked = true;
                                if (answers[number] == "2") radioButton2.Checked = true;
                                if (answers[number] == "3") radioButton3.Checked = true;
                                if (answers[number] == "4") radioButton4.Checked = true;
                            }
                            else if (task[i, 1] == "1")
                                textBox3.Text = answers[number];
                            else if (task[i, 1] == "2")
                            {
                                pictureBox1.Image = picture[Convert.ToInt32(task[i, 3])].Image;
                            }
                        }
                    }
                    path = System.IO.Directory.GetCurrentDirectory() + @"\tests\" + variat[number];
                    webBrowser1.Navigate(new Uri(path));
                    button2.Enabled = true;
                    if (number == 0)
                        button1.Enabled = false;
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "0")
                            {
                                label2.Text = "Выберте вариант ответа:";
                                label4.Text = task[i, 3] + " балла(ов)";
                                radioButton1.Visible = true;
                                radioButton2.Visible = true;
                                radioButton3.Visible = true;
                                radioButton4.Visible = true;
                                textBox3.Visible = false;
                                pictureBox1.Visible = false;
                                button5.Visible = false;
                            }
                            else if (task[i, 1] == "1")
                            {
                                label2.Text = "Введите ответ:";
                                label4.Text = task[i, 2] + " балла(ов)";
                                radioButton1.Visible = false;
                                radioButton2.Visible = false;
                                radioButton3.Visible = false;
                                radioButton4.Visible = false;
                                textBox3.Visible = true;
                                pictureBox1.Visible = false;
                                button5.Visible = false;
                            }
                            else if (task[i, 1] == "2")
                            {
                                label2.Text = "Вставте изображение:";
                                label4.Text = task[i, 2] + " балла(ов)";
                                radioButton1.Visible = false;
                                radioButton2.Visible = false;
                                radioButton3.Visible = false;
                                radioButton4.Visible = false;
                                textBox3.Visible = false;
                                pictureBox1.Visible = true;
                                button5.Visible = true;
                            }
                            break;
                        }
                    }
                    
                break;
                case 1:
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "0")
                            {
                                if (radioButton1.Checked) answers[number] = radioButton1.Text;
                                if (radioButton2.Checked) answers[number] = radioButton2.Text;
                                if (radioButton3.Checked) answers[number] = radioButton3.Text;
                                if (radioButton4.Checked) answers[number] = radioButton4.Text;
                            }
                            else if (task[i, 1] == "1")
                                answers[number] = textBox3.Text;
                            else if (task[i, 1] == "2")
                            {
                                picture[Convert.ToInt32(task[i, 3])].Image = pictureBox1.Image;
                            }
                        }
                    }
                    number++;
                    label1.Text = "Задание(" + (number + 1) + "/" + variation.Count() + "):";
                    radioButton1.Checked = false;
                    radioButton2.Checked = false;
                    radioButton3.Checked = false;
                    radioButton4.Checked = false;
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "0")
                            {
                                if (answers[number] == "1") radioButton1.Checked = true;
                                if (answers[number] == "2") radioButton2.Checked = true;
                                if (answers[number] == "3") radioButton3.Checked = true;
                                if (answers[number] == "4") radioButton4.Checked = true;
                            }
                            else if (task[i, 1] == "1")
                                textBox3.Text = answers[number];
                            else if (task[i, 1] == "2")
                            {
                                pictureBox1.Image = picture[Convert.ToInt32(task[i, 3])].Image;
                            }
                        }
                    }
                    button1.Enabled = true;
                    if (number == variat.Count()-1)
                        button2.Enabled = false;
                    path = System.IO.Directory.GetCurrentDirectory() + @"\tests\" + variat[number];
                    webBrowser1.Navigate(new Uri(path));
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "0")
                            {
                                label2.Text = "Выберите вариант ответа:";
                                label4.Text = task[i, 3] + " балла(ов)";
                                radioButton1.Visible = true;
                                radioButton2.Visible = true;
                                radioButton3.Visible = true;
                                radioButton4.Visible = true;
                                textBox3.Visible = false;
                                pictureBox1.Visible = false;
                                button5.Visible = false;
                            }
                            else if (task[i, 1] == "1")
                            {
                                label2.Text = "Введите ответ:";
                                label4.Text = task[i, 2] + " балла(ов)";
                                radioButton1.Visible = false;
                                radioButton2.Visible = false;
                                radioButton3.Visible = false;
                                radioButton4.Visible = false;
                                textBox3.Visible = true;
                                pictureBox1.Visible = false;
                                button5.Visible = false;
                            }
                            else if (task[i, 1] == "2")
                            {
                                label2.Text = "Вставьте изображение:";
                                label4.Text = task[i, 2] + " балла(ов)";
                                radioButton1.Visible = false;
                                radioButton2.Visible = false;
                                radioButton3.Visible = false;
                                radioButton4.Visible = false;
                                textBox3.Visible = false;
                                pictureBox1.Visible = true;
                                button5.Visible = true;
                            }
                            break;
                        }
                    }
                
                    break;
            }
        }

        private void finishHim()
        {
            global.flag = 1;
            int i;
            for (i = 0; i < global.k; i++)
            {
                if (task[i, 0] + ".html" == variation[number])
                {
                    if (task[i, 1] == "0")
                    {
                        if (radioButton1.Checked) answers[number] = radioButton1.Text;
                        if (radioButton2.Checked) answers[number] = radioButton2.Text;
                        if (radioButton3.Checked) answers[number] = radioButton3.Text;
                        if (radioButton4.Checked) answers[number] = radioButton4.Text;
                    }
                    else if (task[i, 1] == "1")
                        answers[number] = textBox3.Text;
                    else if (task[i, 1] == "2")
                    {
                        picture[Convert.ToInt32(task[i, 3])].Image = pictureBox1.Image;
                    }
                }
            }


            // Все что связано с вордом
            string dirWord = System.IO.Directory.GetCurrentDirectory() + @"\result\";
            object fileName = dirWord + global.surname + "_" + global.name + "_" + global.patronymic + "_" + global.school + "_" + global.course + ".docx";
            object readOnly = false;
            object o = System.Reflection.Missing.Value;
            object f = false;
            object t = true;

            FileStream fWord = File.Create(fileName.ToString());
            fWord.Close();


            oWord = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document oDoc = new Microsoft.Office.Interop.Word.Document();   //System.IO.Directory.GetCurrentDirectory() + @"\results\" + global.name + "_" + global.surname + "_" + global.patronymic + "_" + global.school + "_" + global.course
            oDoc = oWord.Documents.Open(ref fileName, ref o, ref readOnly, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
            Microsoft.Office.Interop.Word.WdWrapType wrap = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;


            // Конеу всего что связно с вордом
            //var app = new Word.Application();
            //app.Visible = true;
            //var doc = app.Documents.Add();
            //var r = doc.Range();
            //r.Text = "Hello Word!";



            int j,k;
            string text="";
            for (i = 0; i < variation.Count(); i++)
            {
                for (j = 0; j < global.k; j++)
                {
                    if (task[j, 0] + ".html" == variation[i])
                    {
                        if (task[j, 1] == "0")
                        {
                            for (k = 0; k < global.l; k++)
                            {

                                string pod = "f" + (k + 1).ToString();
                                if (answers[i] == task[j, 2] && variation[i].Contains(pod)) // && variation[i].IndexOf("f" + (k+1).ToString()) > -1
                                {

                                    catRes[k, 0]++;
                                    catRes[k, 3] += Convert.ToInt32(task[j, 3]);
                                    oDoc.Content.Text += "-----------------------------\r\nФайл вопроса: " + variation[i] + "\r\nOтвет: " + answers[i] + "\r\nРезультат: правильно\r\nКатегория: " + (k+1).ToString() + "\r\n";
                                }
                                else if (answers[i] != task[j, 2] && variation[i].Contains(pod)) // && variation[i].IndexOf("f" + (k+1).ToString()) > -1
                                {

                                    catRes[k, 1]++;
                                    oDoc.Content.Text += "-----------------------------\r\nФайл вопроса: " + variation[i] + "\r\nОтвет: " + answers[i] + "\r\nРезультат: не правильно\r\nКатегория: " + (k + 1).ToString() + "\r\n";
                                }
                            }
                        }
                        else if (task[j, 1] == "1")
                        {
                            for (k = 0; k < global.l; k++)
                            {
                                string pod = "f" + (k + 1).ToString();
                                if (variation[i].Contains(pod))
                                {

                                    catRes[k, 2]++;
                                    oDoc.Content.Text += "###################################################\r\tФайл вопроса: " + variation[i] + "\r\tОтвет: " + answers[i] + "\r\tРезультат: требует проверки\r\tКатегория: " + (k + 1).ToString() + "\r\n###################################################\r\n";
                                }
                            }
                        }
                        else if (task[j, 1] == "2")
                        {
                            for (k = 0; k < global.l; k++)
                            {
                                string pod = "f" + (k + 1).ToString();
                                if (variation[i].Contains(pod))
                                {
                                    catRes[k, 2]++;
                                    oDoc.Content.Text += "###################################################\r\tФайл вопроса:" + variation[i] + "\r\tОтвет: ";
                                    try
                                    {
                                        picture[Convert.ToInt32(task[j, 3])].Image.Save(dirWord + global.surname + "_" + global.name + "_" + global.patronymic + "_" + global.school + "_" + global.course + task[j, 0] + ".jpg");
                                        File.Copy(dirWord + global.surname + "_" + global.name + "_" + global.patronymic + "_" + global.school + "_" + global.course + task[j, 0] + ".jpg", @"S:\\ЕНФ\Результаты\" + global.surname + "_" + global.name + "_" + global.patronymic + "_" + global.school + "_" + global.course + task[j, 0] + ".jpg");
                                        //string darthVauder = dirWord + task[j, 0] + ".jpg";
                                        //Clipboard.SetImage(picture[Convert.ToInt32(task[j, 2])].Image);
                                       // oDoc.Shapes.AddPicture(darthVauder, ref f, ref t, ref o, ref o, ref o, ref o, ref o);  //.Paragraphs[oDoc.Paragraphs.Count].Range.Paste(); //.Shapes.AddPicture(darthVauder, ref f, ref t, ref o, ref o, ref o, ref o, ref o); //.WrapFormat.Type = wrap;
                                        //label1.Text = oDoc.Paragraphs.Count.ToString();
                                    }
                                    catch { }
                                    oDoc.Content.Text += "\r\tРезультат: требует проверки(смотреть в папке)\r\tКатегория: " + (k + 1).ToString() + "\r\n###################################################\r\n";
                                }
                            }
                        }
                    }
                }
            }

            for (i = 0; i < global.l; i++)
            {
                oDoc.Content.Text += "\r\nКатегория: " + (i + 1) + "; Правильно: " + catRes[i, 0] + "; Неправильно: " + catRes[i, 1] + "; Проверка: " + catRes[i, 2] + "Баллы: " + catRes[i, 3];
            }
            //string path = System.IO.Directory.GetCurrentDirectory() + @"\answer\" + global.surname + "_" + global.name + "_" + global.patronymic + "_" + global.school + "_" + global.course + ".txt";
            //File.WriteAllText(path, text, Encoding.UTF8);

            //doc.SaveAs(global.name + "_" + global.surname + "_" + global.patronymic + "_" + global.school + "_" + global.course, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument);
            
            //oDoc.Shapes.AddPicture(pictureBox1.ImageLocation, ref f, ref t, ref o, ref o, ref o, ref o, ref o);
            oDoc.Save();
            oDoc.Close(ref o, ref o, ref o);
            oWord.Quit(ref o, ref o, ref o);
            try
            {
                File.Copy((string)fileName, @"S:\\ЕНФ\Результаты\" + global.surname + "_" + global.name + "_" + global.patronymic + "_" + global.school + "_" + global.course + ".docx");
            }
            catch
            {
            }

            if (global.resultForm == null)
                global.resultForm = new Form3();
            global.resultForm.Show();
            global.testField.Hide();
        }

        private void hernya()
        {
            for (int i = 0; i < answerCatCount.Count(); i++)
            {
                label1.Text += answerCatCount[i];
                label2.Text += global.n;
            }
        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            //global.testField = null;
            //global.mainForm.Show();
            if (global.flag != 1)
            {
                finishHim();
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            selector(1, task, variation);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            selector(0, task, variation);
        }


        private void button4_Click(object sender, EventArgs e)
        {
            if (global.flag != 1)
            {
                finishHim();
            }
        }


        private void button3_Click_1(object sender, EventArgs e)
        {
            //hernya();
            var app = new Word.Application();
            app.Visible = true;
            var doc = app.Documents.Add();
            var r = doc.Range();
            r.Text = "Hello Word!";
            doc.SaveAs(global.name + "_" + global.surname + "_" + global.patronymic + "_" + global.school + "_" + global.course, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            // Проверяем наличие рисунка в буфере
            if (Clipboard.GetImage() != null)
            {
                // Выводим изображение на пикчербокс
                pictureBox1.Image = (Image)Clipboard.GetImage();
                //// Очищаем буфер
                //Clipboard.Clear();
                // Прекращаем обработку
                return;
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (timeLeft > 0)
            {
                timeLeft -= 1;
                int hour, min, sec;
                hour = timeLeft / 3600;
                min = (timeLeft % 3600) / 60;
                sec = (timeLeft % 3600) % 60;
                label3.Text = "Оставшееся время: " + hour.ToString() + ":" + min.ToString() + ":" + sec.ToString();
            }
            else
            {
                timer1.Stop();
                if (global.flag != 1)
                {
                    finishHim();
                }
            }
        }



    }
}
