<repo_name>Genstrom/Vocabulary-Trainer<file_sep>/LanguageLibrary/WordList.cs
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace LanguageLibrary
{
    public class WordList
    {
        private static readonly char[] CharArray = {';'};

        private readonly List<Word> _words = new List<Word>();

        public WordList(string name, params string[] languages)
        {
            Name = name.ToLower();
            Languages = languages;
        }

        private string Name { get; }
        public string[] Languages { get; }

        public static string[] GetLists()
        {
            Folder.CreateFolder();
            var files = Directory.GetFiles(Folder.SpecificFolder)
                .Select(Path.GetFileNameWithoutExtension)
                .ToArray();
            return files;
        }

        public static WordList LoadList(string name)
        {
            Folder.CreateFolder();
            if (!File.Exists(Folder.GetFilePath(name.ToLower()))) return null;
            using var sr = new StreamReader(Folder.GetFilePath(name));
            var line1 = sr.ReadLine();
            if (line1 == null) return null;
            var languages = line1.ToLower().Split(CharArray, StringSplitOptions.RemoveEmptyEntries);
            var wordList = new WordList(name, languages);
            var line = "";
            while ((line = sr.ReadLine()) != null)
                wordList.Add(line.Split(CharArray, StringSplitOptions.RemoveEmptyEntries));
            sr.Close();

            return wordList;
        }

        public void Save()
        {
            LoadList(Name);
            var file = Folder.GetFilePath(Name);
            using var fs = File.Create(file);
            fs.Close();
            foreach (var t in Languages)
                if (!string.IsNullOrWhiteSpace(t))
                    File.AppendAllText(file, $"{t};");
            foreach (var t in _words)
            {
                {
                    File.AppendAllText(file, "\n");
                }
                for (var j = 0; j < Languages.Length; j++) File.AppendAllText(file, $"{t.Translations[j]};");
            }
        }

        public void Add(params string[] translations1)
        {
            if (translations1.Length != Languages.Length) throw new ArgumentException();
            _words.Add(new Word(translations1));
        }

        public bool Remove(int translations, string word)
        {
            if (_words.All(i => i.Translations[translations] != word.ToLower()))
            {
                return false;
            }
            
            var removeAtIndex = _words.IndexOf(_words.First(i => i.Translations[translations] == word.ToLower()));          
            _words.RemoveAt(removeAtIndex);
            Save();
            return true;
            
        }

        public int Count()
        {
            return _words.Count;
        }

        public void List(int sortByTranslation, Action<string[]> showTranslations)
        {
            var sortedTranslations = _words.OrderBy(x => x.Translations[sortByTranslation]).ToArray();


            LoadList(Name);
            foreach (var translation in sortedTranslations) showTranslations(translation.Translations);
        }

        public Word
            GetWordToPractice()
        {
            var rnd = new Random();
            var randomWord = rnd.Next(_words.Count);
            var fromLanguage = rnd.Next(Languages.Length);
            var toLanguage = rnd.Next(Languages.Length);
            while (toLanguage == fromLanguage) toLanguage = rnd.Next(Languages.Length);

            return new Word(fromLanguage,
                toLanguage, _words[randomWord].Translations);
        }
    }
}<file_sep>/LanguageTrainerWinForms/AddNewList.cs
﻿using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using LanguageLibrary;

namespace LanguageTrainerWinForms
{
    public partial class AddNewList : Form
    {
        public AddNewList()
        {
            InitializeComponent();
        }

        private void CreateButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(NameTextBoxInput.Text))
            {
                var name = NameTextBoxInput.Text;
                var languageList = LanguageTextBoxInput.Lines.ToList();
                var languageArray = languageList.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();

                if (languageArray.Length < 2)
                {
                    var caption = "Error Detected in Input";
                    var message = "You need to add atleast 2 langauges. \nThe list will not be saved";
                    var buttons = MessageBoxButtons.OK;
                    MessageBox.Show(message, caption, buttons);
                }
                else
                {
                    var wordList = new WordList(name, languageArray);
                    wordList.Save();
                    Close();
                }
            }
            else
            {
                var caption = "Error Detected in Input";
                var message = "You need to add a name to the list. \nThe list will not be saved";
                var buttons = MessageBoxButtons.OK;
                MessageBox.Show(message, caption, buttons);
            }
        }
        private void CancelButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void AddNewList_Load(object sender, EventArgs e)
        {
            LanguageTextBoxInput.Text = $"Language 1{Environment.NewLine}Language 2{Environment.NewLine}....";
        }

        private void NameTextBoxInput_TextChanged(object sender, EventArgs e)
        {
            LanguageTextBoxInput.Text = string.Empty;
        }
    }
}<file_sep>/Console.Language.Trainer/Program.cs
﻿using System;
using LanguageLibrary;

namespace LanguageTeacher
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintInfo();
                return;
            }

            var inputArray = ArgsToLower(args);
            switch (inputArray[0])
            {
                case "-lists":
                    ListCommand();
                    break;
                case "-new":
                    NewCommand(inputArray);
                    break;
                case "-add":
                    if (inputArray.Length > 1)
                    {
                        AddCommand(inputArray[1]);
                    }
                    else
                    {
                        Console.WriteLine("that list does not exist");
                        Console.WriteLine();
                        PrintInfo();
                    }
                    break;
                case "-remove":
                    RemoveCommand(inputArray);
                    break;
                case "-words":
                    WordsCommand(inputArray);
                    break;
                case "-count":
                    if (inputArray.Length > 1)
                    {
                        CountCommand(inputArray[1]);
                    }
                    else
                    {
                        Console.WriteLine("that list does not exist");
                        Console.WriteLine();
                        PrintInfo();
                    }
                    break;
                case "-practice":
                    if (inputArray.Length > 1)
                    {
                        PracticeCommand(inputArray[1]);
                    }
                    else
                    {
                        Console.WriteLine("that list does not exist");
                        Console.WriteLine();
                        PrintInfo();
                    }
                    break;
            }
        }

        private static void PracticeCommand(string name)
        {


            var wordList = WordList.LoadList(name);
            if (wordList == null)
            {
                Console.WriteLine("That is not a valid list on your computer.");
                return;
            }

            if (wordList.Count() == 0)
            {
                Console.WriteLine("The selected list is empty, you cant practice with an empty list");
                return;
            }

            var languageArray = wordList.Languages;
            var points = 0;
            var tries = 0;
            while (true)
            {
                var practiceWord = wordList.GetWordToPractice();
                Console.WriteLine(
                    $"Here is the {languageArray[practiceWord.FromLanguage]} word {practiceWord.Translations[practiceWord.FromLanguage]}");
                Console.WriteLine(
                    $"Do you know the {languageArray[practiceWord.ToLanguage]} translation?");
                var input = Console.ReadLine().ToLower();
                if (input == practiceWord.Translations[practiceWord.ToLanguage].ToLower())
                {
                    Console.WriteLine("Good job that is the correct answer");
                    points++;
                    tries++;
                }
                else if (!string.IsNullOrWhiteSpace(input))
                {
                    Console.WriteLine("Sorry that is not the correct answer");
                    tries++;
                }

                if (string.IsNullOrWhiteSpace(input))
                {
                    Console.WriteLine($"You got {points} right answers out of {tries}");
                    break;
                }
            }

        }
        private static void CountCommand(string name)
        {
            var wordList = WordList.LoadList(name);
            if (wordList == null)
            {
                Console.WriteLine("That is not a valid list on your computer.");
                return;
            }

            Console.WriteLine($"There are {wordList.Count()} words in the list");
        }

        private static void WordsCommand(string[] args)
        {
            var name = args[1];
            var wordList = WordList.LoadList(name);
            if (wordList == null)
            {
                Console.WriteLine("That is not a valid list on your computer.");
                return;
            }
            
            var languageArray = wordList.Languages;
            var sortBy = GetLanguageIndex(args, languageArray);

            foreach (var languages in languageArray)
            {
                Console.Write(languages.PadLeft(20).ToUpper());
            }
                
            Console.WriteLine();
            wordList.List(sortBy, x =>
            {
                foreach (var t in x)
                {
                    Console.Write(t.PadLeft(20));
                }

                Console.WriteLine();
            });
        }

        private static int GetLanguageIndex(string[] args, string[] languageArray)
        {
            if (args.Length < 3) return 0;
            
            for (var i = 0; i < languageArray.Length; i++)
            {
                if (args[2] == languageArray[i])
                {
                    return i;
                }
            }

            return 0;
        }

        private static void RemoveCommand(string[] args)
        {
            var name = args[1];
            var wordList = WordList.LoadList(name);
            
            if (wordList == null)
            {
                Console.WriteLine("That is not a valid list on your computer.");
                return;
            }
            
            var language = GetLanguageIndex(args,wordList.Languages);

            for (var i = 3; i < args.Length; i++)
            {             
                Console.WriteLine();
                var wasRemoved = wordList.Remove(language, args[i]);
                Console.WriteLine(wasRemoved
                    ? $"The {wordList.Languages[language]} word {args[i]} was removed"
                    : "No Word were removed");
            }
        }

        private static void AddCommand(string name)
        {
            var wordList = WordList.LoadList(name);

            if (wordList == null)
            {
                Console.WriteLine("That is not a valid list on your computer.");
                return;
            }

            AddWords(name, wordList.Languages);
        }

        private static void NewCommand(string[] args)
        {
            var name = args[1];
            if (args.Length < 4)
            {
                Console.WriteLine($"You need to add at least 2 languages you added {args.Length - 2} languages");
                return;
            }

            var languageArray = new string[args.Length - 2];
            for (var i = 2; i < args.Length; i++) languageArray[i - 2] = args[i];
            var wordlist = new WordList(name, languageArray);
            wordlist.Save();
            AddWords(name, languageArray);
        }

        private static void PrintInfo()
        {
            Console.WriteLine("Use any of the following parameters: ");
            Console.WriteLine("-lists");
            Console.WriteLine("-new <list name> <language 1> <language 2> .. <language n>");
            Console.WriteLine("-add <list name>");
            Console.WriteLine("-remove <list name > <language> <word1> <word2>... ");
            Console.WriteLine("-words <listname> <sortByLanguage>");
            Console.WriteLine("-count <listname>");
            Console.WriteLine("-practice <listname>");
        }

        private static void ListCommand()
        {
            var files = WordList.GetLists();
            if (files.Length > 1)
            {
                foreach (var file in files)
                    if (WordList.LoadList(file) != null)
                        Console.WriteLine(file);
            }
            else
            {
                Console.WriteLine("you dont have any lists make a list and then you can see it.");
            }
        }


        private static void AddWords(string name, string[] languages)
        {
            Console.WriteLine("To stop adding words, input an empty string");
            var wordList = WordList.LoadList(name);
            var enterNotPressed = true;
            while (enterNotPressed)
            {
                var words = new string[languages.Length];
                
                for (var i = 0; i < languages.Length; i++)
                {
                    Console.WriteLine(i == 0
                        ? $"Please write the {languages[i]} word"
                        : $"Please write the {languages[i]} translation");
                    
                    var input = Console.ReadLine().ToLower();
                    
                    if (string.IsNullOrWhiteSpace(input))
                    {
                        wordList.Save();
                        enterNotPressed = false;
                        break;
                    }

                    words[i] = input;
                }

                if (enterNotPressed) wordList.Add(words);
            }
        }

        private static string[] ArgsToLower(string[] args)
        {
            var userInput = args;
            for (var i = 0; i < args.Length; i++) userInput[i] = args[i].ToLower();
            return userInput;
        }
    }
}<file_sep>/LanguageTrainerWinForms/PracticeForm.cs
﻿using System;
using System.Windows.Forms;
using LanguageLibrary;

namespace LanguageTrainerWinForms
{
    public partial class PracticeForm : Form
    {
        public PracticeForm(string listName)
        {
            InitializeComponent();
            ListName = listName;
        }

        public PracticeForm()
        {
            InitializeComponent();
        }

        private string ListName { get; }
        private Word WordForPractice { get; set; }
        private int Score { get; set; }
        private int Tries { get; set; }
        private int Fails { get; set; }

        private Word PracticeGenerator()
        {
            var _name = ListName;
            WordForPractice = WordList.LoadList(_name).GetWordToPractice();
            return WordForPractice;
        }

        private void PracticeForm_Load(object sender, EventArgs e)
        {
            PracticeGenerator();
            var _name = ListName;
            var languageArray = WordList.LoadList(_name).Languages;
            PracticeWordBox.Text =
                $"Here is the {languageArray[WordForPractice.FromLanguage]} word {WordForPractice.Translations[WordForPractice.FromLanguage]}\r\n Please submit the {languageArray[WordForPractice.ToLanguage]} translation";
        }

        private void SubmitButton_Click_1(object sender, EventArgs e)
        {
            var _name = ListName;
            var languageArray = WordList.LoadList(_name).Languages;
            var answer = AnswerBox.Text.ToLower();
            AnswerBox.Text = string.Empty;

            if (answer == WordForPractice.Translations[WordForPractice.ToLanguage].ToLower())
            {
                Score++;
                Tries++;
            }
            else
            {
                var caption = "Wrong Answer";
                var message =
                    $"You answered wrong. Your answer was {answer} and the correct answer is {WordForPractice.Translations[WordForPractice.ToLanguage].ToLower()} ";
                var buttons = MessageBoxButtons.OK;
                MessageBox.Show(message, caption, buttons);
                Tries++;
                Fails++;
            }

            PracticeGenerator();
            PracticeWordBox.Text =
                $"Here is the {languageArray[WordForPractice.FromLanguage]} word {WordForPractice.Translations[WordForPractice.FromLanguage]}\r\n Please submit the {languageArray[WordForPractice.ToLanguage]} translation";
            ScoreAmount.Text = Score.ToString();
            FailAmount.Text = Fails.ToString();
            TriesAmount.Text = Tries.ToString();
        }

        private void StopButton_Click_1(object sender, EventArgs e)
        {
            var caption = "End of Session";
            var message =
                $"Out of your {Tries} tries you managed to get {Score} correct answers. You failed on {Fails} words";
            var buttons = MessageBoxButtons.OK;
            MessageBox.Show(message, caption, buttons);
            Close();
        }
    }
}<file_sep>/LanguageTrainerWinForms/MainForm.cs
﻿using System;
using System.Windows.Forms;
using LanguageLibrary;

namespace LanguageTrainerWinForms
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private string FileName { get; set; }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem == null)
            {
                TranslationGrid.Hide();
                InformationBox.Show();
                InformationBox.Text = "this is not a valid list";
                return;
            }

            FileName = listBox1.SelectedItem.ToString();
            var wordList = WordList.LoadList(FileName);
            if (wordList == null)
            {
                return;
            }
            TranslationGrid.Show();
            AddButton.Show();
            NewListButton.Show();
            RemoveButton.Show();
            SaveButton.Show();
            PracticeButton.Show();
            AddButton.Enabled = true;
            SaveButton.Enabled = true;
            RemoveButton.Enabled = true;
            InformationBox.Hide();
            var languageArray = wordList.Languages;
            var sortBy = 0;
            CountLabel.Text = $"There are {wordList.Count()} words in the list";
            TranslationGrid.Rows.Clear();
            TranslationGrid.Columns.Clear();
            TranslationGrid.Refresh();
            foreach (var languages in languageArray)
                TranslationGrid.Columns.Add("newColumnName", languages.ToUpper());
            TranslationGrid.Rows.Clear();

            wordList.List(sortBy, x => { TranslationGrid.Rows.Add(x); });
        }
        private void MainForm_Activated(object sender, EventArgs e)
        {
            listBox1.Show();
            listBox1.Enabled = true;
            ListLabel.Show();
            listBox1.Items.Clear();
            TranslationGrid.Hide();
            var listsOnComputer = WordList.GetLists();

            foreach (var lists in listsOnComputer)
            {
                var wordList = WordList.LoadList(lists);
                if (wordList != null && wordList.Languages.Length > 1)
                {
                    listBox1.Items.Add(lists);
                }
            }
        }

        private void Save()
        {
            if (listBox1.SelectedItem?.ToString() == null)
            {
                return;
            }
            FileName = listBox1.SelectedItem.ToString();
            var modifiedList = new WordList(FileName, WordList.LoadList(FileName).Languages);
            var correctLength = true;

            for (var i = 0; i < TranslationGrid.Rows.Count; i++)
            {
                var words = new string[modifiedList.Languages.Length];
                for (var j = 0; j < words.Length; j++)
                {
                    if (TranslationGrid.Rows[i].Cells[j].Value != null &&
                        !string.IsNullOrWhiteSpace(TranslationGrid.Rows[i].Cells[j].Value.ToString()))
                    {
                        words[j] = TranslationGrid.Rows[i].Cells[j].Value.ToString().ToLower();
                    }
                    else
                    {
                        var emptySlots = TranslationGrid.Rows.Count - modifiedList.Count();
                        for (var k = 0; k < emptySlots; k++) TranslationGrid.Rows.RemoveAt(modifiedList.Count());

                        var caption = "Error Detected in Input";
                        var message =
                            "You did not add a word for every language. \nThe empty indexes will not be saved";
                        var buttons = MessageBoxButtons.OK;
                        MessageBox.Show(message, caption, buttons);
                        correctLength = false;
                        break;
                    }
                    
                }

                if (!correctLength) break;
                modifiedList.Add(words);
                modifiedList.Save();
                CountLabel.Text = $"There are {WordList.LoadList(FileName).Count()} words in the list";
            }
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            TranslationGrid.Rows.Add("");
        }

        private void RemoveButton_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null) FileName = listBox1.SelectedItem.ToString();

            
            if (TranslationGrid.SelectedRows.Count != 0)
            {
                var selectedRows = TranslationGrid.SelectedRows;
                var word = selectedRows[0].Cells[0].Value.ToString();
                WordList.LoadList(FileName).Remove(0, word);
            }
            foreach (DataGridViewRow item in TranslationGrid.SelectedRows) TranslationGrid.Rows.RemoveAt(item.Index);
            CountLabel.Text = $"There are {WordList.LoadList(FileName).Count()} words in the list";
        }

        private void NewListButton_Click(object sender, EventArgs e)
        {
            var newList = new AddNewList();
            newList.Show();
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem == null)
            {
                TranslationGrid.Hide();
                InformationBox.Text = "You need to select a list before you save";
                InformationBox.Show();
            }
            else
            {
                Save();
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            AddButton.Enabled = false;
            SaveButton.Enabled = false;
            RemoveButton.Enabled = false;
        }
        
        private void PracticeButton_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem == null)
            {
                return;
            }
            listBox1.Enabled = false;
            var name = listBox1.SelectedItem.ToString();
            if (WordList.LoadList(name).Count() != 0)
            {
                var practice = new PracticeForm(name);
                TranslationGrid.Hide();
                practice.TopMost = true;
                practice.Show();
            }
            else
            {
                var caption = "Error Detected";
                var message = "The selected list is empty, you cant practice with an empty list";
                var buttons = MessageBoxButtons.OK;
                MessageBox.Show(message, caption, buttons);
                    
            }
        }
    }
}<file_sep>/LanguageTrainerWinForms/Form1.cs
﻿using System;
using System.Windows.Forms;
using LanguageLibrary;

namespace LanguageTrainerWinForms
{
    public partial class Form1 : Form
    {
        public Form1(string name)
        {
            InitializeComponent();
            Name = name;
        }
        
        public string Name { get; }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            
            if (listBox1.SelectedItem != null)
            {
                InformationBox.Hide();
                var name = listBox1.SelectedItem.ToString();
                new Form1(name);
                var languageArray = WordList.LoadList(name).Languages;                
                var sortBy = 0;

                CountLabel.Text = $"There are {WordList.LoadList(name).Count()} words in the list";
                TranslationGrid.Rows.Clear();
                TranslationGrid.Columns.Clear();
                TranslationGrid.Refresh();
                foreach (var languages in languageArray) TranslationGrid.Columns.Add("newColumnName", languages.ToUpper());
                TranslationGrid.Rows.Clear();

                WordList.LoadList(name).List(sortBy, x => { TranslationGrid.Rows.Add(x); });

            }
        }

        private void NewButton_Click(object sender, EventArgs e)
        {
            var newList = new AddNewList();
            newList.Show();
        }

        private void SelectButton_Click(object sender, EventArgs e)
        {
            var name = "";
            if (listBox1.SelectedItem != null) name = listBox1.SelectedItem.ToString();
          
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var newList = new AddNewList();
            newList.Show();
        }

        public void RefreshListbox()
        {
            listBox1.Items.Clear();
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            var addnewlist = new AddNewList();
            listBox1.Show();
            ListLabel.Show();
            listBox1.Items.Clear();
            var vs = WordList.GetLists();
            foreach (var v in vs) listBox1.Items.Add(v);
     
        }

        private void Save()
        {
            var modifiedList = new WordList(Name, WordList.LoadList(Name).Languages);
            var counter = 0;
            for (var i = 0; i < TranslationGrid.Rows.Count; i++)
            {
                var words = new string[modifiedList.Languages.Length];
                for (var j = 0; j < words.Length; j++)
                {
                    if (!string.IsNullOrWhiteSpace(TranslationGrid.Rows[i].Cells[j].Value.ToString()))
                    { 
                        words[j] = TranslationGrid.Rows[i].Cells[j].Value.ToString();
                        counter++;
                    }
                    
                    
                }   
                if (counter == words.Length)
                {
                    modifiedList.Add(words);
                    modifiedList.Save();
                }
               
            }
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            TranslationGrid.Rows.Add("");
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            var modifiedList = new WordList(Name, WordList.LoadList(Name).Languages);

            for (var i = 0; i < TranslationGrid.Rows.Count; i++)
            {
                var words = new string[modifiedList.Languages.Length];
                for (var j = 0; j < words.Length; j++) words[j] = TranslationGrid.Rows[i].Cells[j].Value.ToString();
                modifiedList.Add(words);
                modifiedList.Save();
            }

        }
    }
}