namespace skyscraper8.Skyscraper.Scraper.Storage.Tar;

public class UnixFilePermissions
{
    public UnixFilePermissions()
    {
        UserRead = true;
        UserWrite = true;
        GroupRead = true;
        GroupWrite = true;
    }
    
    public UnixFilePermissions(string permissionString)
    {
        if (permissionString.Length == 7)
            permissionString = permissionString.Substring(4);
        
        string userChar = permissionString.Substring(0, 1);
        string groupChar = permissionString.Substring(1, 1);
        string worldChar = permissionString.Substring(2, 1);
        
        int userInt = Int32.Parse(userChar);
        int groupInt = Int32.Parse(groupChar);
        int worldInt = Int32.Parse(worldChar);

        if (userInt >= 4)
        {
            UserRead = true;
            userInt -= 4;
        }
        if (userInt >= 2)
        {
            UserWrite = true;
            userInt -= 2;
        }
        if (userInt >= 1)
        {
            UserExecute = true;
            userInt -= 1;
        }
        
        if (groupInt >= 4)
        {
            GroupRead = true;
            groupInt -= 4;
        }
        if (groupInt >= 2)
        {
            GroupWrite = true;
            groupInt -= 2;
        }
        if (groupInt >= 1)
        {
            GroupExecute = true;
            groupInt -= 1;
        }
        
        if (worldInt >= 4)
        {
            WorldRead = true;
            worldInt -= 4;
        }
        if (worldInt >= 2)
        {
            WorldWrite = true;
            worldInt -= 2;
        }
        if (worldInt >= 1)
        {
            WorldExecute = true;
            worldInt -= 1;
        }
    }

    public string ToString()
    {
        int user = Fuse(UserRead, UserWrite, UserExecute);
        int group = Fuse(GroupRead, GroupWrite, GroupExecute);
        int world = Fuse(WorldRead, WorldWrite, WorldExecute);
        string result = String.Format("{0}{1}{2}",user,group,world);
        return result;
    }

    public int ToInt32()
    {
        int user = Fuse(UserRead, UserWrite, UserExecute);
        int group = Fuse(GroupRead, GroupWrite, GroupExecute);
        int world = Fuse(WorldRead, WorldWrite, WorldExecute);
        return (user * 100) + (group * 10) + world;
    }

    private int Fuse(bool read, bool write, bool execute)
    {
        int result = 0;
        if (read)
            result += 4;
        if (write)
            result += 2;
        if (execute)
            result += 1;
        return result;
    }
    public bool UserRead { get; set; }
    public bool UserWrite { get; set; }
    public bool UserExecute { get; set; }
    
    public bool GroupRead { get; set; }
    public bool GroupWrite { get; set; }
    public bool GroupExecute { get; set; }
    
    public bool WorldRead { get; set; }
    public bool WorldWrite { get; set; }
    public bool WorldExecute { get; set; }
}
