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

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

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

    public static FileOpenFlags parse(int data) {
        return new FileOpenFlags(Mask.SSH_FXF_READ.presentIn(data),
                                 Mask.SSH_FXF_WRITE.presentIn(data),
                                 Mask.SSH_FXF_APPEND.presentIn(data),
                                 Mask.SSH_FXF_CREAT.presentIn(data),
                                 Mask.SSH_FXF_TRUNC.presentIn(data),
                                 Mask.SSH_FXF_EXCL.presentIn(data));
    }

    public static int format(FileOpenFlags value) {
        int data = 0;
        data = Mask.SSH_FXF_READ.set(value.read, data);
        data = Mask.SSH_FXF_WRITE.set(value.write, data);
        data = Mask.SSH_FXF_APPEND.set(value.append, data);
        data = Mask.SSH_FXF_CREAT.set(value.create, data);
        data = Mask.SSH_FXF_TRUNC.set(value.truncate, data);
        data = Mask.SSH_FXF_EXCL.set(value.exclusively, data);

        return data;
    }

    private FileOpenFlagsFormat() {
    }

    public enum Mask {

        SSH_FXF_READ(0x00000001),
        SSH_FXF_WRITE(0x00000002),
        SSH_FXF_APPEND(0x00000004),
        SSH_FXF_CREAT(0x00000008),
        SSH_FXF_TRUNC(0x00000010),
        SSH_FXF_EXCL(0x00000020);

        public final int mask;

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

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

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

    }
}
