using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Vuforia;

namespace RothenburgAR.Exhibition
{
    public class VuforiaTrackerLoader
    {
        public static TrackerDatabase LoadDatabase(string databaseXmlPath)
        {
            if (!File.Exists(databaseXmlPath))
            {
                throw new FileNotFoundException();
            }

            ObjectTracker tracker = TrackerManager.Instance.GetTracker<ObjectTracker>();
            DataSet dataSet = tracker.CreateDataSet();


            if (dataSet.Load(databaseXmlPath, VuforiaUnity.StorageType.STORAGE_ABSOLUTE))
            {
                var trackableBehaviours = new List<TrackableBehaviour>();
                IEnumerable<TrackableBehaviour> tbs = TrackerManager.Instance.GetStateManager().GetTrackableBehaviours();
                foreach (TrackableBehaviour tb in tbs)
                {
                    if (tb.name != "New Game Object" || !tb.gameObject.activeSelf)
                    {
                        continue;
                    }
                    tb.gameObject.name = "New Trackable Object";
                    trackableBehaviours.Add(tb);
                }

                return new TrackerDatabase
                {
                    Path = databaseXmlPath,
                    DataSet = dataSet,
                    TrackableBehaviours = trackableBehaviours
                };
            }
            else
            {
                throw new Exception("Could not load DataSet");
            }
        }

        public static bool ActivateDataset(DataSet dataSet)
        {
            bool success = true;
            ObjectTracker tracker = TrackerManager.Instance.GetTracker<ObjectTracker>();
            tracker.Stop();
            if (!tracker.ActivateDataSet(dataSet))
            {
                Debug.Log("<color=yellow>Failed to Activate DataSet</color>");
                success = false;
            }

            if (!tracker.Start())
            {
                Debug.Log("<color=yellow>Tracker Failed to Start.</color>");
                success = false;
            }
            return success;
        }
    }

    public struct TrackerDatabase
    {
        public string Path { get; set; }
        public List<TrackableBehaviour> TrackableBehaviours { get; set; }
        public DataSet DataSet { get; set; }
    }
}