using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Google.Protobuf;
using Net.Eagle0.Eagle.Api;
using UnityEngine;

namespace eagle {
    public class ClientPregeneratedText : MonoBehaviour {
        public static ClientPregeneratedText Provider = null;

        public void Load(PregeneratedText incomingText) {
            var directoryPath = Path.GetDirectoryName(_localPregeneratedTextPath);
            Directory.CreateDirectory(directoryPath);

            _pregeneratedTexts = incomingText.Entries.ToDictionary(x => x.TextId, x => x.Text);
            Hash = incomingText.Hash;

            File.WriteAllBytes(_localPregeneratedTextPath, incomingText.ToByteArray());
        }

        public void Awake() {
            _localPregeneratedTextPath = Path.Combine(
                    Application.persistentDataPath,
                    "eagle0",
                    "Resources",
                    "pregenerated_text.txt");

            if (File.Exists(_localPregeneratedTextPath)) {
                var data = File.ReadAllBytes(_localPregeneratedTextPath);
                var fromFile = PregeneratedText.Parser.ParseFrom(data);
                _pregeneratedTexts = fromFile.Entries.ToDictionary(x => x.TextId, x => x.Text);
                Hash = fromFile.Hash;
            } else {
                _pregeneratedTexts = new();
                Hash = 0;
            }

            Provider = this;
        }

        public Int64 Hash { get; private set; }
        public bool TryGetText(string textId, out string text) =>
                _pregeneratedTexts.TryGetValue(textId, out text);

        private string _localPregeneratedTextPath;
        private Dictionary<string, string> _pregeneratedTexts = new();
    }
}