static void SetActive(DataGridViewRow r, bool NewActive)
 {
     if (!MediaFileDateFixer.SetActive(r.DataBoundItem as Entry, NewActive))
     {
         return;
     }
     f.gridMain.InvalidateRow(r.Index);
     RefreshApplyButton();
 }
 static void ToggleActive(DataGridViewRow r, bool Invalidate = true)
 {
     if (!MediaFileDateFixer.ToggleActive(r.DataBoundItem as Entry))
     {
         return;
     }
     if (Invalidate)
     {
         f.gridMain.InvalidateRow(r.Index);
     }
     RefreshApplyButton();
 }
        static void RefreshFilter()
        {
            f.gridMain.SuspendDrawing();
            int NewFilter = MediaFileDateFixer.GetDetectionFilter();

            foreach (DataGridViewRow r in f.gridMain.Rows)
            {
                bool NewVisibility = ((NewFilter & (int)(r.DataBoundItem as Entry).Detection) == 0);
                if (r.Visible == NewVisibility)
                {
                    continue;
                }
                if (f.gridMain.CurrentCell != null && f.gridMain.CurrentCell.RowIndex == r.Index)
                {
                    f.gridMain.CurrentCell = null;
                }
                if (r.Selected)
                {
                    r.Selected = false;
                }
                r.Visible = NewVisibility;
            }
            f.gridMain.ResumeDrawing();
        }
        [STAThread] static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (args.Length >= 1)
            {
                if (!Directory.Exists(args[0]))
                {
                    MessageBox.Show("Directory '" + args[0] + "' does not exist", "Error");
                    return;
                }

                MediaFileDateFixer.Directory = args[0];
            }

            f = new MediaFileDateFixerForm();

            f.gridMain.AutoGenerateColumns = false;
            f.gridMain.AutoSize            = false;
            f.gridMain.ShowCellToolTips    = true;
            f.gridMain.DataSource          = MediaFileDateFixer.GetEntries();
            f.gridMain.ReadOnly            = false;
            f.gridMain.Columns.Add(MakeCol <DataGridViewCheckBoxCell>("", "ColActive", 0));
            f.gridMain.Columns.Add(MakeCol <DataGridViewTextBoxCell>("Name", "ColFileName", 3));
            f.gridMain.Columns.Add(MakeCol <DataGridViewTextBoxCell>("File Date", "ColFileDate", 2));
            f.gridMain.Columns.Add(MakeCol <DataGridViewTextBoxCell>("Meta Date", "ColMetaDate", 2));
            f.gridMain.Columns.Add(MakeCol <DataGridViewTextBoxCell>("Detection", "ColDetection", 1));
            f.gridMain.Columns.Add(MakeCol <DataGridViewTextBoxCell>("Error", "ColError", 1));
            f.gridMain.Columns.Add(MakeCol <DataGridViewTextBoxCell>("Difference", "ColDiff", 1));
            f.gridMain.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            f.gridMain.AutoSizeRowsMode    = DataGridViewAutoSizeRowsMode.None;

            f.gridMain.ColumnHeaderMouseClick += (object sender, DataGridViewCellMouseEventArgs e) =>
            {
                SortOrder NewOrder = (f.gridMain.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending);
                foreach (DataGridViewColumn c in f.gridMain.Columns)
                {
                    c.HeaderCell.SortGlyphDirection = SortOrder.None;
                }
                MediaFileDateFixer.SortEntries(f.gridMain.Columns[e.ColumnIndex].DataPropertyName, (NewOrder == SortOrder.Descending));
                f.gridMain.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = NewOrder;
                RefreshFilter();
                f.gridMain.Invalidate();
            };

            f.gridMain.CellFormatting += (object sender, DataGridViewCellFormattingEventArgs e) =>
            {
                Entry en = f.gridMain.Rows[e.RowIndex].DataBoundItem as Entry;
                if (en.MetaDate == DateTime.MinValue)
                {
                    e.CellStyle.SelectionBackColor = e.CellStyle.BackColor = SystemColors.ControlDark; e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor = SystemColors.ControlText;
                }
                else if (!en.Active && en.FileDate == en.MetaDate + Entry.FixOffset)
                {
                    e.CellStyle.SelectionBackColor = e.CellStyle.BackColor = SystemColors.ControlLight; e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor = SystemColors.ControlText;
                }
                else if (e.ColumnIndex == 2 && !en.Active)
                {
                    e.CellStyle.SelectionBackColor = e.CellStyle.BackColor = Color.Green;              e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor = Color.White;
                }
                else if (e.ColumnIndex == 3 && en.Active)
                {
                    e.CellStyle.SelectionBackColor = e.CellStyle.BackColor = Color.Green;              e.CellStyle.SelectionForeColor = e.CellStyle.ForeColor = Color.White;
                }
            };

            f.gridMain.KeyPress += (object sender, KeyPressEventArgs e) =>
            {
                if (e.KeyChar != ' ')
                {
                    return;
                }
                if (f.gridMain.SelectedRows.Count == 0)
                {
                    return;
                }
                bool NewActive = !((f.gridMain.CurrentCell.Selected ? f.gridMain.CurrentCell.OwningRow : f.gridMain.SelectedRows[0]).DataBoundItem as Entry).Active;
                foreach (DataGridViewRow r in f.gridMain.SelectedRows)
                {
                    if (r.Visible)
                    {
                        SetActive(r, NewActive);
                    }
                }
                if (f.gridMain.CurrentCell.ColumnIndex == 0)
                {
                    ToggleActive(f.gridMain.CurrentCell.OwningRow, false);
                }
            };

            f.gridMain.CellClick += (object s, DataGridViewCellEventArgs e) =>
            {
                if (e.RowIndex >= 0 && e.ColumnIndex == 2)
                {
                    SetActive(f.gridMain.Rows[e.RowIndex], false);
                }
                if (e.RowIndex >= 0 && e.ColumnIndex == 3)
                {
                    SetActive(f.gridMain.Rows[e.RowIndex], true);
                }
            };

            f.gridMain.CellContentClick += (object s, DataGridViewCellEventArgs e) =>
            {
                if (e.RowIndex >= 0 && e.ColumnIndex == 0)
                {
                    ToggleActive(f.gridMain.Rows[e.RowIndex]);
                }
            };

            f.gridMain.CellContentDoubleClick += (object s, DataGridViewCellEventArgs e) =>
            {
                if (e.RowIndex >= 0 && e.ColumnIndex == 0)
                {
                    ToggleActive(f.gridMain.Rows[e.RowIndex]);
                }
            };

            f.gridMain.CellDoubleClick += (object s, DataGridViewCellEventArgs e) =>
            {
                Entry en = (e.RowIndex >= 0 ? f.gridMain.Rows[e.RowIndex].DataBoundItem as Entry : null);
                if (e.ColumnIndex == 1 && en != null)
                {
                    System.Diagnostics.Process.Start("explorer", en.FileName);
                }
                if (e.ColumnIndex == 4 && en != null)
                {
                    MediaFileDateFixer.MessageBoxAllMetaData(en.FileName);
                }
            };

            MediaFileDateFixer.OnProgress = (EProgressState State, EProgressType Type, int Progress) =>
            {
                if (f.Disposing || f.IsDisposed)
                {
                    return;
                }
                if (f.InvokeRequired)
                {
                    try { f.Invoke((Action) delegate { MediaFileDateFixer.OnProgress(State, Type, Progress); }); } catch (Exception) { } return;
                }

                if (Type == EProgressType.CountInit)
                {
                    f.pbProgress.Maximum = Progress;
                    f.pbProgress.Value   = 0;
                }
                else if (Type == EProgressType.CountIncrement)
                {
                    if (f.pbProgress.Value < f.gridMain.RowCount)
                    {
                        f.gridMain.InvalidateRow(f.pbProgress.Value);
                    }
                    f.pbProgress.SetProgressNoAnimation(f.pbProgress.Value + 1);
                }
                else if (Type == EProgressType.Finish)
                {
                    f.gridMain.DataSource = MediaFileDateFixer.GetEntries();
                    RefreshApplyButton();
                    RefreshFilter();
                    f.pbProgress.Value = 0;
                }
                f.lblState.Text = State.ToString().Replace('_', ' ');
            };

            Action <ThreadStart> RunThreaded      = (ThreadStart ts) => { Thread t = new Thread(ts); t.IsBackground = true; t.Start(); };
            EventHandler         DisableSelection = (object s, EventArgs e) => { f.gridMain.ClearSelection(); };
            Action <bool>        Lock             = (bool DoLock) => { if (f.Disposing || f.IsDisposed)
                                                                       {
                                                                           return;
                                                                       }
                                                                       f.Invoke((Action) delegate
                {
                    f.gridMain.Enabled           = f.btnFilter.Enabled = !DoLock;
                    f.gridMain.SelectionChanged -= DisableSelection;
                    if (DoLock)
                    {
                        f.gridMain.SelectionChanged += DisableSelection; f.gridMain.ClearSelection(); f.btnApply.Enabled = false;
                    }
                }); };

            f.btnFilter.Click += (object s, EventArgs e) =>
            {
                ContextMenu context = new ContextMenu();
                foreach (Entry.EDetection Name in Enum.GetValues(typeof(Entry.EDetection)))
                {
                    MenuItem i = context.MenuItems.Add(Name.ToString().Replace('_', ' '));
                    i.Checked = ((MediaFileDateFixer.GetDetectionFilter() & (int)Name) == 0);
                    i.Tag     = Name;
                    i.Click  += (object sender, EventArgs ee) =>
                    {
                        (sender as MenuItem).Checked ^= true;
                        ToggleFilter((Entry.EDetection)(sender as MenuItem).Tag);
                        (sender as MenuItem).GetContextMenu().Show(f.btnFilter, new Point(0, 0));
                    };
                }
                context.Show(f.btnFilter, new Point(0, 0));
            };

            f.numOffsetHour.ValueChanged   += (object sender, EventArgs e) => { Entry.FixOffset = new TimeSpan((int)f.numOffsetHour.Value, (int)f.numOffsetMinute.Value, 0); f.gridMain.Invalidate(); };
            f.numOffsetMinute.ValueChanged += (object sender, EventArgs e) => { Entry.FixOffset = new TimeSpan((int)f.numOffsetHour.Value, (int)f.numOffsetMinute.Value, 0); f.gridMain.Invalidate(); };
            f.btnApply.Click      += (object s, EventArgs e) => { Lock(true); RunThreaded(() => { MediaFileDateFixer.Apply(); Lock(false); }); };
            f.btnEnableAll.Click  += (object s, EventArgs e) => { SetAllActive(true); };
            f.btnDisableAll.Click += (object s, EventArgs e) => { SetAllActive(false); };

            RefreshApplyButton();
            f.gridMain.Enabled = f.btnFilter.Enabled = f.btnApply.Enabled = false;

            f.btnOpen.Click += (object sender, EventArgs e) =>
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.RootFolder   = Environment.SpecialFolder.MyComputer;
                fbd.SelectedPath = MediaFileDateFixer.Directory;
                if (fbd.ShowDialog() != DialogResult.OK)
                {
                    fbd.Dispose(); return;
                }
                MediaFileDateFixer.Directory = fbd.SelectedPath;
                fbd.Dispose();
                f.gridMain.DataSource = null;
                RunThreaded(() => { MediaFileDateFixer.Query(); Lock(false); });
            };

            f.Shown += (object sender, EventArgs e) =>
            {
                if (MediaFileDateFixer.Directory == null)
                {
                    f.btnOpen.PerformClick();
                }
                else
                {
                    RunThreaded(() => { MediaFileDateFixer.Query(); Lock(false); });
                }
            };

            Application.Run(f);
        }
 static void ToggleFilter(Entry.EDetection DetectionToggle)
 {
     MediaFileDateFixer.ToggleFilter(DetectionToggle);
     RefreshFilter();
     RefreshApplyButton();
 }
 static void RefreshApplyButton()
 {
     f.btnApply.Text    = f.btnApply.Tag.ToString().Replace("#", MediaFileDateFixer.GetActiveCount().ToString());
     f.btnApply.Enabled = (MediaFileDateFixer.GetActiveCount() > 0);
 }