// Copyright (C) 2013 panacoran <panacoran@users.sourceforge.jp>
// Copyright (C) 2003 Daisuke Arai <darai@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$

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

namespace PtSim.Controls
{
    /// <summary>
    /// 拡張子がptのファイルを選択するTreeView
    /// </summary>
    public partial class PtFileTreeView : TreeView
    {
        private string _topDir;
        private readonly FileSystemWatcher _watcher = new FileSystemWatcher();

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public PtFileTreeView()
        {
            InitializeComponent();

            _watcher.Changed += FilesystemWatcherHandler;
            _watcher.Created += FilesystemWatcherHandler;
            _watcher.Deleted += FilesystemWatcherHandler;
            _watcher.Renamed += FilesystemWatcherHandler;
        }

        /// <summary>
        /// トップディレクトリを取得または設定する。
        /// </summary>
        public string RootDirectory
        {
            set
            {
                _topDir = value;
                BeginUpdate();
                SetNodes(Nodes, _topDir);
                EndUpdate();
                _watcher.Path = _topDir;
                _watcher.EnableRaisingEvents = true;
            }
        }

        /// <summary>
        /// 選択されているファイルの相対パスを取得または設定する。
        /// </summary>
        public string SelectedFile
        {
            get
            {
                if (SelectedNode == null)
                    return null;
                var path = SelectedNode.FullPath + ".pt";
                return File.Exists(Path.Combine(_topDir, path)) ? path : null;
            }
            set
            {
                if (value == null)
                    return;
                var nodes = Nodes;
                var path = value.Substring(0, value.Length - 3);
                TreeNode target = null;
                foreach (var name in path.Split(new[] {PathSeparator}, StringSplitOptions.RemoveEmptyEntries))
                {
                    var found = nodes.Find(name, false);
                    if (found.Length == 0)
                        return;
                    target = found[0];
                    nodes = target.Nodes;
                }
                SelectedNode = target;
            }
        }

        private static void SetNodes(TreeNodeCollection nodes, string path)
        {
            nodes.Clear();
            if (!Directory.Exists(path))
                return;
            foreach (var dir in Directory.GetDirectories(path))
            {
                var key = Path.GetFileName(dir);
                SetNodes(nodes.Add(key, key, 0, 0).Nodes, dir);
            }
            foreach (var file in Directory.GetFiles(path, "*.pt"))
            {
                var key = Path.GetFileNameWithoutExtension(file);
                nodes.Add(key, key, 2, 2);
            }
        }

        private void FilesystemWatcherHandler(Object source, FileSystemEventArgs e)
        {
            Invoke(new MethodInvoker(UpdateNodes));
        }

        private void UpdateNodes()
        {
            BeginUpdate();
            var selected = SelectedFile;
            SetNodes(Nodes, _topDir);
            SelectedFile = selected;
            EndUpdate();            
        }

        /// <summary>
        /// BeforeExpandイベントを処理する。
        /// </summary>
        /// <param name="e">TreeViewCancelEventArgs</param>
        protected override void OnBeforeExpand(TreeViewCancelEventArgs e)
        {
            base.OnBeforeExpand(e);
            e.Node.ImageIndex = e.Node.SelectedImageIndex = 1;
        }

        /// <summary>
        /// BeforeCollapseイベントを処理する。
        /// </summary>
        /// <param name="e">TreeViewCancelEventArgs</param>
        protected override void OnBeforeCollapse(TreeViewCancelEventArgs e)
        {
            base.OnBeforeCollapse(e);
            e.Node.ImageIndex = e.Node.SelectedImageIndex = 0;
        }
    }
}