using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ResBuilder
{
    static class Tools
    {
        public static readonly Encoding UTF8 = new UTF8Encoding(false, false);
        public static readonly Encoding UTF8_BOM = new UTF8Encoding(true, false);
        public static string DecodeUTF8(byte[] data)
        {
            if (data.Length > 3)
            {
                if ((data[0] == 0xEF) && (data[1] == 0xBB) && (data[2] == 0xBF))
                {
                    return UTF8_BOM.GetString(data);
                }
            }
            return UTF8.GetString(data);
        }

        public static bool ExistCharInLineBefore(string str, int endIdex, char c)
        {
            for (int i = endIdex - 1; i >= 0; i--)
            {
                if (str[i] == '\n')
                {
                    return false;
                }
                if (str[i] == c)
                {
                    return true;
                }
            }
            return false;
        }


        public static string FindUpDirectory(string dirName, int rlev = 3)
        {
            var curPath = Environment.CurrentDirectory;
            var curNode = new DirectoryInfo(curPath);

            var uplev = 0;
            while (curNode.Parent != null && uplev < rlev)
            {
                var ret = curNode.GetDirectories(dirName, SearchOption.TopDirectoryOnly);
                if (ret.Length > 0)
                {
                    return ret[0].FullName;
                }
                else
                {
                    curNode = curNode.Parent;
                }
                uplev++;
            }
            return null;
        }

        internal static uint HashFileNameWithoutExtension(string relativeFilePath)
        {
            uint hash = 0;
            for (int i = 0; i < relativeFilePath.Length; i++)
            {
                uint cc = relativeFilePath[i];
                if (cc == '.')
                {
                    break;
                }
                if (cc >= '0' && cc <= '9')
                {
                    cc = cc - '0';
                }
                else if (cc >= 'A' && cc <= 'Z')
                {
                    cc = cc - 'A' + 10;
                }
                else if (cc >= 'a' && cc <= 'z')
                {
                    cc = cc - 'a' + 34;
                }
                else
                {
                    cc = 59;
                }
                hash += (hash << 5) + cc;
            }
            return hash;
        }
    }
}