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

namespace RememorySDK
{
    public class SetupAndroid
    {
        private const string captureInfoFileName = "captureinfo.json";
        private const string depthDatFileName = "depth.dat";

        public static IEnumerator Init(string DirName)
        {
            if(!File.Exists(Path.Combine(Application.persistentDataPath, DirName, captureInfoFileName)))
            {
                yield return CoroutineHandler.StartStaticCoroutine(FileCopyFromStreamingToPersistent(DirName, captureInfoFileName));
            }

            string captureInfoPath = Path.Combine(Application.persistentDataPath, DirName, captureInfoFileName);
            string _file = File.ReadAllText(captureInfoPath);
            CaptureDPInfo captureInfo = JsonUtility.FromJson<CaptureDPInfo>(_file);

            // Setup Video
            if(!File.Exists(Path.Combine(Application.persistentDataPath, DirName, captureInfo.videoFileName)))
            {
                yield return CoroutineHandler.StartStaticCoroutine(DataCopyFromStreamingToPersistent(DirName, captureInfo.videoFileName));
            }
            // Setup Depth
            if(!File.Exists(Path.Combine(Application.persistentDataPath, DirName, depthDatFileName)))
            {
                yield return CoroutineHandler.StartStaticCoroutine(DataCopyFromStreamingToPersistent(DirName, depthDatFileName));
            }
        }

        private static IEnumerator FileCopyFromStreamingToPersistent(string DirName,string fileName)
        {
            string path = Path.Combine(Application.streamingAssetsPath, DirName, fileName);
            var www = UnityWebRequest.Get(path);
            yield return www.SendWebRequest();
            string toPath = Path.Combine(Application.persistentDataPath, DirName, fileName);

            if (!Directory.Exists(Path.GetDirectoryName((toPath))))
            {
                Directory.CreateDirectory(Path.GetDirectoryName((toPath)));
            }

            yield return null;

            File.WriteAllText(toPath, www.downloadHandler.text);
        }

        private static IEnumerator DataCopyFromStreamingToPersistent(string DirName, string fileName)
        {
            string path = Path.Combine(Application.streamingAssetsPath, DirName, fileName);
            var www = UnityWebRequest.Get(path);
            yield return www.SendWebRequest();
            string toPath = Path.Combine(Application.persistentDataPath, DirName, fileName);

            if (!Directory.Exists(Path.GetDirectoryName((toPath))))
            {
                Directory.CreateDirectory(Path.GetDirectoryName((toPath)));
            }

            yield return null;

            File.WriteAllBytes (toPath, www.downloadHandler.data);
        }
    }
}