using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Windows.Media;
using System.Drawing;
using System.IO;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using System.Diagnostics;

namespace Revit.Addin.ScheduleImages
{
    /// <summary>
    /// UI used to indicate the progress form.
    /// </summary>
    public partial class MainForm : System.Windows.Forms.Form
    {
       Autodesk.Revit.DB.Document m_rvtDoc;
        /// <summary>
        /// Ctor of progress indicator.
        /// </summary>
        /// <param name="formText">Form title.</param>
        /// <param name="progressMsg">Progress message.</param>
        /// <param name="progressMaximum">Maximum of the progress.</param>
       public MainForm(Document rvtDoc)
        {
           InitializeComponent();

           m_rvtDoc = rvtDoc;
           textBoxFrom.Text = @"D:\Revit\PI\Perf";
           textBoxCount.Text = "1000";
        }
       
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
           DialogResult rtn = folderBrowserDialog.ShowDialog();
           if (rtn == DialogResult.OK)
           {
              textBoxFrom.Text = folderBrowserDialog.SelectedPath;              
           }
        }

        private void buttonRun_Click(object sender, EventArgs e)
        {
           // find all rvt models firstly        
           if (!Directory.Exists(textBoxFrom.Text))
           {
              MessageBox.Show("The specified source directory doesn't exist!", AppConfig.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
              return;
           }
           int imageSum = int.Parse(textBoxCount.Text);
           //
           // find all rvt files
           DirectoryInfo di = new DirectoryInfo(textBoxFrom.Text);
           FileInfo[] images = di.GetFiles("*.jpg", SearchOption.AllDirectories);
           int imageCount = images.Count();
           if (imageCount <= 0)
           {
              MessageBox.Show("No any .jpg models found under specified folder.", AppConfig.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
              return;
           }
           // 
           // logging setup
           string logFile = string.Format("{0}\\log.{1}.txt", textBoxFrom.Text, DateTime.Now.ToString("yyyy-mm-dd hh.mm.ss"));
           FileStream logger = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
           TextWriterTraceListener logLn = new TextWriterTraceListener(logger);
           Trace.Listeners.Add(logLn);
           Trace.AutoFlush = true;
           //
           // start to parse the rvt models now
           List<ElementId> imageInst = new List<ElementId>();
           Random random = new Random(imageCount);
           ProgressForm progress = new ProgressForm(AppConfig.AppName, "Start import images...", imageSum);
           progress.StartPosition = FormStartPosition.CenterScreen;
           progress.Show(this);
           //
           Transaction tran = new Transaction(m_rvtDoc);
           tran.Start("batch import");
           for (int ii = 0; ii < imageSum; ii++)
           {
              int index = random.Next(0, imageCount - 1);
              string imgFile = images[index].FullName;
              FileInfo fi = new FileInfo(imgFile);
              progress.performProgressBarSteps(string.Format("Adding image file({0})...{1}/{2}", fi.Name, ii + 1, imageSum));
              Trace.WriteLine(fi.Name + " Inserted");
              try
              {
                 ImageImportOptions opt = new ImageImportOptions();
                 Element outElem;
                 bool succeed = m_rvtDoc.Import(imgFile, opt, m_rvtDoc.ActiveView, out outElem);
                 if (succeed && outElem != null)
                    imageInst.Add(outElem.Id);
              }
              catch (System.Exception ex)
              {
                 Trace.WriteLine(string.Format("{0}: Open failed:{1}.", imgFile, ex.Message));
              }
           }

           try
           {
              m_rvtDoc.Delete(imageInst);
              tran.Commit();
           }
           catch (Exception ex)
           {
              MessageBox.Show("Failed to import images, ex: " + ex.Message);
           }

           Trace.Flush();
           Trace.Close();
           logger.Close();
           progress.Close();
           //
           // message info
           MessageBox.Show("Done", AppConfig.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

       List<Type> findElemTypes()
        {
           List<Type> elemTypes = new List<Type>();
           elemTypes.Add(typeof(Stairs));
           elemTypes.Add(typeof(Railing));
           return elemTypes;
        }

       private void buttonDbg_Click(object sender, EventArgs e)
       {
          BasicFileInfo bfi = BasicFileInfo.Extract(@"c:\gbXML_Sandbox2013 - 2014.rvt");
          Trace.WriteLine(bfi.IsSavedInCurrentVersion);
          Trace.WriteLine(bfi.SavedInVersion);
       }
    }
}
