package com.jscape.inet.sftp.protocol.v3.marshaling;

import com.jscape.inet.sftp.protocol.v3.messages.FileAttributeFlags;

/**
 * @author Alex Usun
 */
public class FileAttributeFlagsFormat {

    public static FileAttributeFlags parse(int data) {
        return new FileAttributeFlags(Mask.SSH_FILEXFER_ATTR_SIZE.presentIn(data),
                                      Mask.SSH_FILEXFER_ATTR_UIDGID.presentIn(data),
                                      Mask.SSH_FILEXFER_ATTR_PERMISSIONS.presentIn(data),
                                      Mask.SSH_FILEXFER_ATTR_ACMODTIME.presentIn(data),
                                      Mask.SSH_FILEXFER_ATTR_EXTENDED.presentIn(data));
    }

    public static int format(FileAttributeFlags value) {
        int data = 0;
        data = Mask.SSH_FILEXFER_ATTR_SIZE.set(value.sizeAttributePresent, data);
        data = Mask.SSH_FILEXFER_ATTR_UIDGID.set(value.userIdGroupIdAttributesPresent, data);
        data = Mask.SSH_FILEXFER_ATTR_PERMISSIONS.set(value.permissionsAttributePresent, data);
        data = Mask.SSH_FILEXFER_ATTR_ACMODTIME.set(value.accessModificationTimeAttributesPresent, data);
        data = Mask.SSH_FILEXFER_ATTR_EXTENDED.set(value.extendedAttributesPresent, data);

        return data;
    }

    private FileAttributeFlagsFormat() {
    }

    public enum Mask {

        SSH_FILEXFER_ATTR_SIZE(0x00000001),
        SSH_FILEXFER_ATTR_UIDGID(0x00000002),
        SSH_FILEXFER_ATTR_PERMISSIONS(0x00000004),
        SSH_FILEXFER_ATTR_ACMODTIME(0x00000008),
        SSH_FILEXFER_ATTR_EXTENDED(0x80000000);

        public final int code;

        Mask(int code) {
            this.code = code;
        }

        public boolean presentIn(int flags) {
            return (flags & this.code) == this.code;
        }

        public int set(boolean value, int flags) {
            return value ? flags | this.code : flags;
        }
    }
}
