using System.Linq;
using System.IO;
using System.Windows.Forms;
using LabelerCore.Data;

namespace UserControls
{
    public partial class RawDataExplorer : UserControl
    {
        private DirectoryInfo _rawDataFolder;
        private VehicleInfo[] _displayedVehicles;
        public delegate void FolderChangedHandler(DirectoryInfo rawDataFolder);
        public event FolderChangedHandler FolderChanged;
        
        public DirectoryInfo RawDataFolder
        {
            get{ return _rawDataFolder; }
            set{
                if(FolderChanged != null)
                    FolderChanged(value);
                _rawDataFolder = value;
            }
        }

        public TrainingData  TrainData
        {
            get {  return recordTable.TrainData; }
            set {recordTable.TrainData = value;  }
        }
     
        public RawDataExplorer()
        {
            InitializeComponent();
            RawDataFolder = new DirectoryInfo(@"../../../../data/FRQ/KP-CE");
            PopulateTreeView();     
        }

        public void PopulateTreeView()
        {
            TreeNode rootNode;                    
            rawDataTreeView.Nodes.Clear();
            if (RawDataFolder.Exists)
            {
                rootNode = new TreeNode(RawDataFolder.Name);
                rootNode.Tag = RawDataFolder;
                GetDirectories(RawDataFolder.GetDirectories(), rootNode);
                rawDataTreeView.Nodes.Add(rootNode);
            }
        }

        private void GetDirectories(DirectoryInfo[] subDirs,
                                    TreeNode nodeToAddTo)
        {
            TreeNode aNode;
            DirectoryInfo[] subSubDirs;
            foreach (DirectoryInfo subDir in subDirs)
            {
                aNode = new TreeNode(subDir.Name, 0, 0);
                aNode.Tag = subDir;
                aNode.ImageKey = "folder";
                subSubDirs = subDir.GetDirectories();
                if (subSubDirs.Length != 0)
                {
                    GetDirectories(subSubDirs, aNode);
                }
                nodeToAddTo.Nodes.Add(aNode);
            }
        }

        protected void rawDataTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode newSelected = e.Node;
            DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
            _displayedVehicles = RecordFinder.GetVehiclesInfo(nodeDirInfo);
            recordTable.ShowItems(_displayedVehicles);
        }

        public void UpdateDGV() {
            recordTable.ShowItems(_displayedVehicles);
        }

    }
}
