using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;

namespace Show_Tracker
{
    public partial class Form1 : Form
    {
        private List<Label> titles;
        private List<PictureBox> covers;
        private Point labelLocations;
        private int typeToShow;
        private List<Button> buttons;
        private List<Movie> movies;
        private List<Show> currentlyWatching;
        private List<Show> completedShows;
        private List<NumericUpDown> selectors;

        public Form1()
        {
            InitializeComponent();

            typeToShow = 0;
            labelLocations = new Point(238, 130);

            movies = new List<Movie>();
            currentlyWatching = new List<Show>();
            completedShows = new List<Show>();

            titles = new List<Label>();
            covers = new List<PictureBox>();
            buttons = new List<Button>();
            selectors = new List<NumericUpDown>();

            if (File.Exists("MovieDatabase.txt"))
            {
                String movieDatabase = System.IO.File.ReadAllText("MovieDatabase.txt");
                movies = JsonConvert.DeserializeObject<List<Movie>>(movieDatabase);
            }

            if (File.Exists("WatchingDatabase.txt"))
            {
                String watchingDatabase = System.IO.File.ReadAllText("WatchingDatabase.txt");
                currentlyWatching = JsonConvert.DeserializeObject<List<Show>>(watchingDatabase);
            }

            if (File.Exists("CompletedDatabase.txt"))
            {
                String completedDatabase = System.IO.File.ReadAllText("CompletedDatabase.txt");
                completedShows = JsonConvert.DeserializeObject<List<Show>>(completedDatabase);
            }
        }

        private void clearSearch()
        {
            labelLocations = new Point(238, 130);
            Controls.Remove(IntroText);
            foreach (Label theLabel in titles)
            {
                Controls.Remove(theLabel);
            }
            foreach (PictureBox cover in covers)
            {
                Controls.Remove(cover);
            }
            foreach (Button button in buttons)
            {
                Controls.Remove(button);
            }
            foreach (NumericUpDown numUpDown in selectors)
            {
                Controls.Remove(numUpDown);
            }
        }

        private void populateMovie(Search theMovie)
        {
            PictureBox cover = new PictureBox();
            covers.Add(cover);
            cover.Location = new Point(labelLocations.X - 226, labelLocations.Y);
            cover.Size = new Size(150, 225);
            if (theMovie.Poster != "N/A")
            {
                try
                {
                    cover.Load(theMovie.Poster);
                }
                catch(Exception)
                {
                    cover.Image = Properties.Resources.noposter;
                }
            }
            else
            {
                cover.Image = Properties.Resources.noposter;
            }
            cover.SizeMode = PictureBoxSizeMode.Zoom;
            Controls.Add(cover);

            Label titleText = new Label();
            titles.Add(titleText);
            titleText.Text = "Title:";
            titleText.Location = new Point(labelLocations.X - 66, labelLocations.Y + 10);
            titleText.Font = new Font(titleText.Font, FontStyle.Bold);
            titleText.Size = new Size(36, 13);
            titleText.AutoSize = true;
            Controls.Add(titleText);

            Label title = new Label();
            titles.Add(title);
            title.Text = theMovie.Title;
            // title.Size = new Size(200, 13);
            title.Location = new Point(labelLocations.X, labelLocations.Y + 10);
            title.AutoSize = true;
            Controls.Add(title);
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            clearSearch();

            String search = searchBox.Text;
            if (typeToShow == 0)
            {
                search = "http://www.omdbapi.com/?s=" + search;
            }
            else if (typeToShow == 1)
            {
                search = "http://www.omdbapi.com/?type=movie&s=" + search;
            }
            else if (typeToShow == 2)
            {
                search = "http://www.omdbapi.com/?type=series&s=" + search;
            }

            String result;
            using (WebClient client = new WebClient())
            {
                result = client.DownloadString(search);
            }

            Movies searchMovies = new Movies();
            searchMovies = JsonConvert.DeserializeObject<Movies>(result);
            searchBox.Text = "";

            if (searchMovies.Response != "False")
            {
                foreach (Search theMovie in searchMovies.Search)
                {
                    if (theMovie.Type == "game")
                    {
                        continue;
                    }

                    theMovie.Year = Regex.Replace(theMovie.Year, "[^ -~]", "");

                    populateMovie(theMovie);

                    Label yearText = new Label();
                    titles.Add(yearText);
                    yearText.Text = "Year:";
                    yearText.Location = new Point(labelLocations.X - 66, labelLocations.Y + 33);
                    yearText.Font = new Font(yearText.Font, FontStyle.Bold);
                    yearText.Size = new Size(36, 13);
                    yearText.AutoSize = true;
                    Controls.Add(yearText);

                    Label year = new Label();
                    titles.Add(year);
                    year.Text = theMovie.Year;
                    // year.Size = new Size(200, 13);
                    year.Location = new Point(labelLocations.X, labelLocations.Y + 33);
                    year.AutoSize = true;
                    Controls.Add(year);

                    if (theMovie.Type.Equals("movie"))
                    {
                        Boolean exists = false;

                        foreach (Movie checkMovie in movies)
                        {
                            if (checkMovie.imdbID == theMovie.imdbID)
                            {
                                exists = true;
                            }
                        }

                        if (exists)
                        {
                            Label existsText = new Label();
                            titles.Add(existsText);
                            existsText.Text = "This movie is already in your collection!";
                            existsText.Location = new Point(labelLocations.X, labelLocations.Y + 60);
                            existsText.Font = new Font(existsText.Font, FontStyle.Bold);
                            existsText.Size = new Size(36, 13);
                            existsText.AutoSize = true;
                            Controls.Add(existsText);
                        }
                        else
                        {
                            Button addToLibrary = new Button();
                            addToLibrary.Tag = theMovie.imdbID;
                            buttons.Add(addToLibrary);
                            addToLibrary.BackgroundImage = Properties.Resources.addToLibrary;
                            addToLibrary.BackgroundImageLayout = ImageLayout.Zoom;
                            addToLibrary.FlatStyle = FlatStyle.Flat;
                            addToLibrary.FlatAppearance.BorderSize = 0;
                            addToLibrary.Size = new Size(155, 58);
                            addToLibrary.Location = new Point(labelLocations.X, labelLocations.Y + 60);
                            Controls.Add(addToLibrary);
                            addToLibrary.Click += new EventHandler(addToLibrary_Click);
                        }
                    }
                    else if (theMovie.Type.Equals("series"))
                    {

                        int exists = 0;

                        foreach (Show theShow in currentlyWatching)
                        {
                            if (theShow.imdbID == theMovie.imdbID)
                            {
                                exists = 1;
                            }
                        }

                        foreach (Show theShow in completedShows)
                        {
                            if (theShow.imdbID == theMovie.imdbID)
                            {
                                exists = 2;
                            }
                        }

                        if (exists == 1)
                        {
                            Label existsText = new Label();
                            titles.Add(existsText);
                            existsText.Text = "This show is already currently being watched!";
                            existsText.Location = new Point(labelLocations.X, labelLocations.Y + 60);
                            existsText.Font = new Font(existsText.Font, FontStyle.Bold);
                            existsText.Size = new Size(36, 13);
                            existsText.AutoSize = true;
                            Controls.Add(existsText);
                        }
                        else if (exists == 2)
                        {
                            Label existsText = new Label();
                            titles.Add(existsText);
                            existsText.Text = "This show has already been completed!";
                            existsText.Location = new Point(labelLocations.X, labelLocations.Y + 60);
                            existsText.Font = new Font(existsText.Font, FontStyle.Bold);
                            existsText.Size = new Size(36, 13);
                            existsText.AutoSize = true;
                            Controls.Add(existsText);
                        }
                        else
                        {
                            Button addToCurrWatch = new Button();
                            addToCurrWatch.Tag = theMovie.imdbID;
                            buttons.Add(addToCurrWatch);
                            addToCurrWatch.BackgroundImage = Properties.Resources.addToCurrWatch;
                            addToCurrWatch.BackgroundImageLayout = ImageLayout.Zoom;
                            addToCurrWatch.FlatStyle = FlatStyle.Flat;
                            addToCurrWatch.FlatAppearance.BorderSize = 0;
                            addToCurrWatch.Size = new Size(175, 58);
                            addToCurrWatch.Location = new Point(labelLocations.X, labelLocations.Y + 60);
                            Controls.Add(addToCurrWatch);
                            addToCurrWatch.Click += new EventHandler(addToCurrWatch_Click);

                            Button addToCompleted = new Button();
                            addToCompleted.Tag = theMovie.imdbID;
                            buttons.Add(addToCompleted);
                            addToCompleted.BackgroundImage = Properties.Resources.addToCompleted;
                            addToCompleted.BackgroundImageLayout = ImageLayout.Zoom;
                            addToCompleted.FlatStyle = FlatStyle.Flat;
                            addToCompleted.FlatAppearance.BorderSize = 0;
                            addToCompleted.Size = new Size(120, 58);
                            addToCompleted.Location = new Point(labelLocations.X, labelLocations.Y + 115);
                            Controls.Add(addToCompleted);
                            addToCompleted.Click += new EventHandler(addToCompleted_Click);
                        }
                    }

                    labelLocations = new Point(labelLocations.X, labelLocations.Y + 250);
                }
            }
        }

        private void addToLibrary_Click(object sender, EventArgs e)
        {
            Button clickedButton = (Button)sender;
            String jsonquery = "http://www.omdbapi.com/?i=" + clickedButton.Tag;

            String result;
            using (WebClient client = new WebClient())
            {
                result = client.DownloadString(jsonquery);
            }

            Movie movie = new Movie();
            movie = JsonConvert.DeserializeObject<Movie>(result);

            movies.Add(movie);

            String export = JsonConvert.SerializeObject(movies);
            File.WriteAllText(@"MovieDatabase.txt", export);
        }

        private void addToCurrWatch_Click(object sender, EventArgs e)
        {
            Button clickedButton = (Button)sender;
            String jsonquery = "http://www.omdbapi.com/?i=" + clickedButton.Tag;

            String result;
            using (WebClient client = new WebClient())
            {
                result = client.DownloadString(jsonquery);
            }

            Show show = new Show();
            show = JsonConvert.DeserializeObject<Show>(result);

            currentlyWatching.Add(show);

            String export = JsonConvert.SerializeObject(currentlyWatching);
            File.WriteAllText(@"WatchingDatabase.txt", export);
        }

        private void addToCompleted_Click(object sender, EventArgs e)
        {
            Button clickedButton = (Button)sender;
            String jsonquery = "http://www.omdbapi.com/?i=" + clickedButton.Tag;

            String result;
            using (WebClient client = new WebClient())
            {
                result = client.DownloadString(jsonquery);
            }

            Show show = new Show();
            show = JsonConvert.DeserializeObject<Show>(result);

            completedShows.Add(show);

            String export = JsonConvert.SerializeObject(completedShows);
            File.WriteAllText(@"CompletedDatabase.txt", export);
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            typeToShow = 0;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            typeToShow = 1;
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            typeToShow = 2;
        }

        private void CheckEnterKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                searchButton.PerformClick();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            clearSearch();
            movies.Sort((x, y) => x.Title.CompareTo(y.Title));
            foreach (Movie movie in movies)
            {
                populateMovie(movie);
                insertCross(movie, 1);
                populateMovieAdvanced(movie);
                labelLocations = new Point(labelLocations.X, labelLocations.Y + 250);
            }
        }

        private void populateMovieAdvanced(Movie movie)
        {
            Label releasedText = new Label();
            titles.Add(releasedText);
            releasedText.Text = "Released:";
            releasedText.Location = new Point(labelLocations.X - 66, labelLocations.Y + 56);
            releasedText.Font = new Font(releasedText.Font, FontStyle.Bold);
            releasedText.Size = new Size(36, 13);
            releasedText.AutoSize = true;
            Controls.Add(releasedText);

            Label released = new Label();
            titles.Add(released);
            released.Text = movie.Released;
            // title.Size = new Size(200, 13);
            released.Location = new Point(labelLocations.X, labelLocations.Y + 56);
            released.AutoSize = true;
            Controls.Add(released);

            Label directorText = new Label();
            titles.Add(directorText);
            directorText.Text = "Director:";
            directorText.Location = new Point(labelLocations.X - 66, labelLocations.Y + 79);
            directorText.Font = new Font(directorText.Font, FontStyle.Bold);
            directorText.Size = new Size(36, 13);
            directorText.AutoSize = true;
            Controls.Add(directorText);

            Label director = new Label();
            titles.Add(director);
            director.Text = movie.Director;
            // year.Size = new Size(200, 13);
            director.Location = new Point(labelLocations.X, labelLocations.Y + 79);
            director.AutoSize = true;
            Controls.Add(director);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            clearSearch();
            currentlyWatching.Sort((x, y) => x.Title.CompareTo(y.Title));
            foreach (Show show in currentlyWatching)
            {
                populateMovie(show);
                populateMovieAdvanced(show);

                Label seasonLabel = new Label();
                titles.Add(seasonLabel);
                seasonLabel.Text = "Season: ";
                seasonLabel.Location = new Point(labelLocations.X-66, labelLocations.Y + 115);
                Controls.Add(seasonLabel);
                seasonLabel.AutoSize = true;

                NumericUpDown season = new NumericUpDown();
                selectors.Add(season);
                season.Location = new Point(labelLocations.X-11, labelLocations.Y + 115);
                season.Tag = show.imdbID;
                Controls.Add(season);
                season.Size = new Size(60, 10);
                season.Value = show.season;
                season.ValueChanged += new EventHandler(season_Changed);

                Label episodeLabel = new Label();
                titles.Add(episodeLabel);
                episodeLabel.Text = "Episode: ";
                episodeLabel.Location = new Point(labelLocations.X-66, labelLocations.Y + 140);
                Controls.Add(episodeLabel);
                episodeLabel.AutoSize = true;

                NumericUpDown episode = new NumericUpDown();
                selectors.Add(episode);
                episode.Location = new Point(labelLocations.X - 11, labelLocations.Y + 140);
                Controls.Add(episode);
                episode.Tag = show.imdbID;
                episode.Size = new Size(60, 10);
                episode.Value = show.episode;
                episode.ValueChanged += new EventHandler(episode_Changed);

                Button completeShow = new Button();
                buttons.Add(completeShow);
                completeShow.Tag = show.imdbID;
                completeShow.BackgroundImage = Properties.Resources.addToCompleted;
                completeShow.BackgroundImageLayout = ImageLayout.Zoom;
                completeShow.FlatStyle = FlatStyle.Flat;
                completeShow.FlatAppearance.BorderSize = 0;
                completeShow.Size = new Size(100, 58);
                completeShow.Location = new Point(labelLocations.X - 66, labelLocations.Y + 160);
                Controls.Add(completeShow);
                completeShow.Click += new EventHandler(currentCompleted_Click);

                insertCross(show, 2);

                labelLocations = new Point(labelLocations.X, labelLocations.Y + 250);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            clearSearch();
            completedShows.Sort((x, y) => x.Title.CompareTo(y.Title));
            foreach (Show show in completedShows)
            {
                populateMovie(show);
                populateMovieAdvanced(show);
                insertCross(show, 3);

                labelLocations = new Point(labelLocations.X, labelLocations.Y + 250);
            }
        }

        private void insertCross(Movie movie, int mode)
        {
            Button cross = new Button();
            buttons.Add(cross);
            cross.Tag = movie.imdbID;
            cross.BackgroundImage = Properties.Resources.cross;
            cross.BackgroundImageLayout = ImageLayout.Zoom;
            cross.FlatStyle = FlatStyle.Flat;
            cross.FlatAppearance.BorderSize = 0;
            cross.Size = new Size(15, 15);
            cross.Location = new Point(labelLocations.X + 300, labelLocations.Y);
            Controls.Add(cross);
            if (mode == 1)
            {
                cross.Click += new EventHandler(cross_ClickMovies);
            }
            else if (mode == 2)
            {
                cross.Click += new EventHandler(cross_ClickWatching);
            }
            else
            {
                cross.Click += new EventHandler(cross_ClickCompleted);
            }
        }

        private void cross_ClickMovies(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            Movie theMovie = new Movie();
            foreach (Movie movie in movies)
            {
                if (button.Tag.Equals(movie.imdbID))
                {
                    theMovie = movie;
                }
            }
            movies.Remove(theMovie);

            String export = JsonConvert.SerializeObject(movies);
            File.WriteAllText(@"MovieDatabase.txt", export);

            button1.PerformClick();
        }

        private void cross_ClickWatching(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            Show theShow = new Show();
            foreach (Show show in currentlyWatching)
            {
                if (button.Tag.Equals(show.imdbID))
                {
                    theShow = show;
                }
            }
            currentlyWatching.Remove(theShow);

            String export = JsonConvert.SerializeObject(currentlyWatching);
            File.WriteAllText(@"WatchingDatabase.txt", export);

            button2.PerformClick();
        }

        private void cross_ClickCompleted(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            Show theShow = new Show();
            foreach (Show show in completedShows)
            {
                if (button.Tag.Equals(show.imdbID))
                {
                    theShow = show;
                }
            }
            completedShows.Remove(theShow);

            String exportComplete = JsonConvert.SerializeObject(completedShows);
            File.WriteAllText(@"CompletedDatabase.txt", exportComplete);

            button3.PerformClick();
        }

        private void season_Changed(object sender, EventArgs e)
        {
            NumericUpDown upDown = (NumericUpDown)sender;

            Show theShow = new Show();
            foreach (Show show in currentlyWatching)
            {
                if (upDown.Tag.Equals(show.imdbID))
                {
                    theShow = show;
                }
            }

            theShow.season = upDown.Value;
            String export = JsonConvert.SerializeObject(currentlyWatching);
            File.WriteAllText(@"WatchingDatabase.txt", export);
        }

        private void episode_Changed(object sender, EventArgs e)
        {
            NumericUpDown upDown = (NumericUpDown)sender;

            Show theShow = new Show();
            foreach (Show show in currentlyWatching)
            {
                if (upDown.Tag.Equals(show.imdbID))
                {
                    theShow = show;
                }
            }

            theShow.episode = upDown.Value;
            String export = JsonConvert.SerializeObject(currentlyWatching);
            File.WriteAllText(@"WatchingDatabase.txt", export);
        }

        private void currentCompleted_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            Show theShow = new Show();
            foreach (Show show in currentlyWatching)
            {
                if (button.Tag.Equals(show.imdbID))
                {
                    theShow = show;
                }
            }
            currentlyWatching.Remove(theShow);
            completedShows.Add(theShow);

            String exportWatching = JsonConvert.SerializeObject(currentlyWatching);
            File.WriteAllText(@"WatchingDatabase.txt", exportWatching);

            String exportComplete = JsonConvert.SerializeObject(completedShows);
            File.WriteAllText(@"CompletedDatabase.txt", exportComplete);

            button2.PerformClick();
        }
    }
}
