﻿using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using RememorySDK.API;

namespace RememorySDK
{
    [CustomEditor(typeof(RememoryPlayer))]
    public class RememoryPlayerEditor : Editor
    {
        private RememoryPlayer playerTarget;
        private SerializedObject m_Object;
        private bool isUpdateCaptureDir = false;
        private bool isStreamingAssetsPathError = false;

        public void OnEnable()
        {
            playerTarget = (RememoryPlayer)target;
            m_Object = new SerializedObject(target);
        }

        public override void OnInspectorGUI()
        {
            m_Object.Update();
            EditorGUI.BeginChangeCheck();

            SerializedProperty m_isFollowCamera = m_Object.FindProperty("isFollowCamera");
            SerializedProperty m_FilePath = m_Object.FindProperty("captureDir");

            GUILayout.Label("Custom Properties", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(m_FilePath);



            var evt = Event.current;

            var dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
            GUI.Box(dropArea, "Drag & Drop");
            int id = GUIUtility.GetControlID(FocusType.Passive);

            switch (evt.type)
            {
                case EventType.DragUpdated:
                case EventType.DragPerform:
                    if (!dropArea.Contains(evt.mousePosition)) break;

                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    DragAndDrop.activeControlID = id;

                    if (evt.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();

                        foreach (var draggedObject in DragAndDrop.objectReferences)
                        {
                            var draggedObjectPath = AssetDatabase.GetAssetPath(draggedObject);
                            var streamingAssetsPath = "Assets/StreamingAssets/";

                            isStreamingAssetsPathError = !draggedObjectPath.Contains(streamingAssetsPath);

                            var folderPath = draggedObjectPath.Replace(streamingAssetsPath, "");

                            string lastFolderName = Path.GetFileName(AssetDatabase.GetAssetPath(draggedObject));
                            m_FilePath.stringValue = folderPath;
                            playerTarget.captureDir = folderPath;
                            isUpdateCaptureDir = true;
                            Undo.RecordObject(playerTarget, "Change Property");
                            EditorUtility.SetDirty(playerTarget);
                        }
                        DragAndDrop.activeControlID = 0;
                    }
                    Event.current.Use();
                    break;
            }


            Color backgroundColor = GUI.backgroundColor;
            if (!string.IsNullOrEmpty(m_FilePath.stringValue) || isUpdateCaptureDir)
            {
                var fullPath = Path.Combine(Application.streamingAssetsPath, m_FilePath.stringValue);

                isUpdateCaptureDir = false;
                string notExistsFileName = string.Empty;

                if (isStreamingAssetsPathError)
                {
                    notExistsFileName = "Folder location error: Please select [Assets/StreamingAssets/*]";
                }
                else if (!System.IO.Directory.Exists(fullPath))
                {
                    notExistsFileName = "Select the correct captureDir";
                }
                else
                {
                    var datPath = CaptureAPI.GetDatPath(fullPath);
                    var captureInfo = CaptureAPI.GetCaptureInfo(fullPath);
                    var videoPath = CaptureAPI.GetVideoPath(fullPath);

                    if (!System.IO.File.Exists(datPath))
                    {
                        notExistsFileName = "depth.dat not loaded\n";
                    }
                    if (captureInfo == null)
                    {
                        notExistsFileName += "captureinfo.json not loaded\n";
                    }
                    if (!System.IO.File.Exists(videoPath))
                    {
                        notExistsFileName += "videoFile not loaded\n";
                    }
                }

                if (!string.IsNullOrEmpty(notExistsFileName))
                {
                    GUI.backgroundColor = Color.red;
                    EditorGUILayout.BeginVertical();

                    EditorGUILayout.HelpBox(notExistsFileName,
                                            MessageType.Error);


                    EditorGUILayout.EndVertical();
                }
                else
                {
                    GUI.backgroundColor = Color.green;
                    EditorGUILayout.BeginVertical();

                    EditorGUILayout.HelpBox("Rememory player is setup",
                                            MessageType.Info);
                    EditorGUILayout.EndVertical();
                }
            }

            GUI.backgroundColor = backgroundColor;
            int meshModeIndex = (int)playerTarget.meshMode;

            string[] meshModeEnumStr = Enum.GetNames(typeof(MeshMode));

            meshModeIndex = EditorGUILayout.Popup("meshMode", meshModeIndex, meshModeEnumStr);

            if (playerTarget.MeshModeType != (MeshMode)Enum.ToObject(typeof(MeshMode), meshModeIndex))
            {
                playerTarget.MeshModeType = (MeshMode)Enum.ToObject(typeof(MeshMode), meshModeIndex);
            }

            m_isFollowCamera.boolValue = EditorGUILayout.Toggle("isFollowCamera", m_isFollowCamera.boolValue);

            if (playerTarget.IsFollowCamera != m_isFollowCamera.boolValue)
            {
                playerTarget.IsFollowCamera = m_isFollowCamera.boolValue;
            }

            m_Object.ApplyModifiedProperties();

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(playerTarget, "Change Property");
                EditorUtility.SetDirty(playerTarget);
            }
        }
    }
}