﻿using Echoic.Binary;
using System;
using System.IO;

namespace HceProgress.Library
{
    public class SavegameDetect : IDetect
    {
        private readonly int suffixLength = 9;

        // Documents\My Games\Halo CE\savegames\<profile name>\savegame.bin
        // <profile name> = Last selected profile by HCE
        public string Find()
        {
            string path = $"{ProfilePath}\\{ProfileName}\\savegame.bin";

            if (!File.Exists(path))
            {
                throw new FileNotFoundException("Cannot detect savegame.bin. File not found.");
            }

            return path;
        }

        // Documents\My Games\Halo CE
        private string HceSavePath => $"{MyDocuments}\\My Games\\Halo CE";

        // Documents\My Games\Halo CE\savegames
        private string ProfilePath => $"{HceSavePath}\\savegames";

        // User documents
        private string MyDocuments => Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Documents\My Games\Halo CE\lastprof.txt
        private string ProfileName => Parse();

        private string Parse()
        {
            string data = TrimSuffix(TrimSpaces(ReadText()));

            string name = string.Empty;

            for (int i = 0; i < data.Length; i++)
            {
                if (data[data.Length - i - 1] != '\\')
                {
                    name += data[data.Length - i - 1];
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine(ReverseName(name));

            return ReverseName(name);
        }

        private string ReadText()
        {
            if (!File.Exists(HceSavePath + "\\lastprof.txt"))
            {
                throw new FileNotFoundException("Cannot read lastprof.txt. File not found.");
            }

            return File.ReadAllText(HceSavePath + "\\lastprof.txt");
        }

        private string TrimSpaces(string text)
        {
            return text.TrimEnd('\0');
        }

        private string TrimSuffix(string text)
        {
            return text.Substring(0, text.Length - suffixLength);
        }

        private string ReverseName(string name)
        {
            var charArray = name.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }
    }
}
