﻿/* Copyright (c) 2016 Seth Ballantyne <seth.ballantyne@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

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 MapControl;
using System.IO;

namespace Map_Editor
{
    /// <summary>
    /// Loads all the available tiles on a seperate thread so they're cached.
    /// </summary>
    public partial class LoadTilesProgressForm : Form
    {
        // These will be used to populate the palette list view
        TileFrame[] loadedTiles;

        public LoadTilesProgressForm()
        {
            InitializeComponent();
        }

        private void LoadTilesProgressForm_Shown(object sender, EventArgs e)
        {
            // The form begins processing tiles as soon as it's displayed.
            // Calling RunWorkerAsync() Fires a DoWork event which is 
            // handled below in backgroundWorker_DoWork
            backgroundWorker.RunWorkerAsync();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                TileFrame[] tiles = FileManager.GetBitmapFrameFromTiles(3, backgroundWorker);
                if (tiles != null)
                {
                    // Just because tiles != null does not mean something has
                    // not gone wrong. GetBitmapFrameFromTiles returns an empty
                    // TileFrame[] if there were no tiles to load in the tiles
                    // directory. MainForm.UpdatePallete() will display an error
                    // message if no tiles were loaded and kill the program.
                    // Just making a note that that particular situation is possible
                    // but not handled here.
                    backgroundWorker.ReportProgress(100, tiles as TileFrame[]);
                }
            }
            // Handling exeptions here instead of in RunWorkerCompleted
            // because  the Debugger in VS doesn't work properly otherwise.
            catch (OutOfMemoryException oome)
            {
                // Generated by FileManager.GetTiles().
                // Caused by corrupt BMP file or bad pixel format.
                //StringBuilder sb = new StringBuilder();

                sb.AppendFormat("Error: {0}",
                    oome.Message);

                MessageBox.Show(sb.ToString(), "OutOfMemoryException caught",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                backgroundWorker.CancelAsync();
            }
            catch (DirectoryNotFoundException dnfe)
            {
                // part of the search path is missing
                //StringBuilder sb = new StringBuilder();

                sb.AppendFormat("Error: {0} {1}{2}Aborting.", dnfe.Message, Environment.NewLine, Environment.NewLine);
                MessageBox.Show(sb.ToString(), "DirectoryNotFoundException caught", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                backgroundWorker.CancelAsync();
            }
            catch (UnauthorizedAccessException uae)
            {
                sb.AppendFormat("Error: {0}", uae.Message);

                MessageBox.Show(sb.ToString(), "UnauthorizedAccessException caught", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                backgroundWorker.CancelAsync();
            }
            catch(Exception)
            {   
                // !# Add custom MessageBox.
                throw;
            }
        }

        // Called when backgroundWorker.ReportProgress is called - this will be called
        // from within MapControl.dll, not here. 
        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage != 100)
            {
                label.Text = "Loading tile: " + e.UserState as string;
                //System.Diagnostics.Debug.Print(label.Text);
            }
            else
            {
                loadedTiles = e.UserState as TileFrame[];
            }
        }

        // Executed when the user cancels, an error occurs or the dialog
        // has successfully completed its task.
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                DialogResult = DialogResult.Cancel;
            }
            else
            {
                // loadedMap = e.Result as Map;
                this.DialogResult = DialogResult.OK;

            }
        }

        public TileFrame[] GetTiles()
        {
            return loadedTiles;
        }
    }
}
