// Copyright (C) 2013 panacoran <panacoran@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: FileChangeWatcher.cs 450 2013-05-25 14:32:09Z panacoran $

using System.IO;
using System.Windows.Forms;

namespace Protra.Lib.Config
{
    /// <summary>
    /// ファイルの変更を監視するクラス
    /// </summary>
    public class FileChangeWatcher
    {
        private const int Interval = 500;
        private const int MaxRetry = 5;
        private int _retryCount;
        private readonly FileSystemWatcher _watcher;
        private readonly System.Threading.Timer _timer;

        /// <summary>
        /// ファイルを処理するデリゲートを取得または設定する。
        /// </summary>
        public MethodInvoker ProcessFile { private get; set; }

        /// <summary>
        /// 変更の監視が有効かを取得または設定する。
        /// </summary>
        public bool Enabled
        {
            get { return _watcher.EnableRaisingEvents; }
            set { _watcher.EnableRaisingEvents = value; }
        }

        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="path">変更を監視するファイル</param>
        public FileChangeWatcher(string path)
        {
            var dir = Path.GetDirectoryName(path);
            var file = Path.GetFileName(path);
            if (dir == null || file == null)
                return;
            _watcher = new FileSystemWatcher {Path = dir, Filter = file, NotifyFilter = NotifyFilters.LastWrite};
            _watcher.Changed += watcher_Changed;

            _timer = new System.Threading.Timer(timer_Elapsed);
        }

        void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            _retryCount = 0;
            _timer.Change(Interval, 0); // 連続してChangeイベントが発生したときはタイマーを再設定する。
        }

        private void timer_Elapsed(object info)
        {
            try
            {
                if (ProcessFile != null)
                    ProcessFile();
            }
            catch (IOException exception)
            {
                if (++_retryCount > MaxRetry)
                    MessageBox.Show(exception.Message, _watcher.Filter, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    _timer.Change(Interval, 0); // retry
            }
        }
    }
}
