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 Test
{
    public partial class Form4 : 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;
        int timeLeft = 5400;
        
        public Form4()
        {
            InitializeComponent();
        }

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

            return wordArray;
        }

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

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

            string dir2 = System.IO.Directory.GetCurrentDirectory() + @"\tests\Режим2\";
            //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(dir2, "f*.html", System.IO.SearchOption.TopDirectoryOnly).Count();
            while (System.IO.Directory.GetFiles(dir2, "f" + i.ToString() + "*.html", System.IO.SearchOption.TopDirectoryOnly).Count() != 0)
            {
                l++;
                i++;
            }
            string line;
            // Обьявляем файл
            path2 = System.IO.Directory.GetCurrentDirectory() + @"\tests\Режим2\conf.txt";
            System.IO.StreamReader filee = new System.IO.StreamReader(path2);
            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(dir2, "f" + (p + 1).ToString() + "*.html", System.IO.SearchOption.TopDirectoryOnly);
                for (i = 0; i < findFiles.Count(); i++)
                    findFiles[i] = findFiles[i].Replace(dir2, "");

                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;
                }
            }*/

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

            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++;
            }

            path2 = System.IO.Directory.GetCurrentDirectory() + @"\tests\Режим2\" + variation[number];
            webBrowser1.Navigate(new Uri(path2));
            label1.Text = "Задание(" + (number + 1) + "/" + variation.Count() + "):";
            for (i = 0; i < global.k; i++)
            {
                if (task[i, 0] + ".html" == variation[number])
                {

                    if (task[i, 1] == "1")
                    {
                        label4.Text = task[i, 3] + " балла(ов)";
                    }
                    break;
                }
            }
            label3.Text = "Оставшееся время: 1:30:00";
            //label4.Text = task[23,2];
        }



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

            string path2;
            int i;
            switch (a)
            {

                case 0:
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "1")
                                answers[number] = textBox3.Text;
                        }
                    }
                    number--;
                    label1.Text = "Задание(" + (number + 1) + "/" + variation.Count() + "):";
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "1")
                                textBox3.Text = answers[number];
                        }
                    }
                    path2 = System.IO.Directory.GetCurrentDirectory() + @"\tests\Режим2\" + variat[number];
                    webBrowser1.Navigate(new Uri(path2));
                    button2.Enabled = true;
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "1")
                            {
                                label4.Text = task[i, 3] + " балла(ов)";
                            }
                            break;
                        }
                    }

                    break;
                case 1:
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "1")
                                answers[number] = textBox3.Text;
                        }
                    }
                    number++;
                    label1.Text = "Задание(" + (number + 1) + "/" + variation.Count() + "):";
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "1")
                                textBox3.Text = answers[number];
                        }
                    }
                    if (number == variat.Count() - 1)
                        button2.Enabled = false;
                    path2 = System.IO.Directory.GetCurrentDirectory() + @"\tests\Режим2\" + variat[number];
                    webBrowser1.Navigate(new Uri(path2));
                    for (i = 0; i < global.k; i++)
                    {
                        if (task[i, 0] + ".html" == variat[number])
                        {
                            if (task[i, 1] == "1")
                            {
                                label4.Text = task[i, 3] + " балла(ов)";
                            }
                            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] == "1")
                        answers[number] = textBox3.Text;
                }
            }


            // Все что связано с вордом
            string dirWord = System.IO.Directory.GetCurrentDirectory() + @"\result\Режим2\";
            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] == "1")
                        {
                            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";
                                }
                            }
                        }
                    }
                }
            }

            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.result == null)
                global.result = new Form5();
            global.result.Show();
            global.mode2.Hide();
        }

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

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

        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();
                }
            }
        }
    }
}
