'use strict';

var hex = require('./hex.js');
var hsl = require('./hsl.js');
var keyword = require('./keyword.js');
var rgb = require('./rgb.js');
var constants = require('../constants.js');

/* IMPORT */
/* MAIN */
const Color = {
    /* VARIABLES */
    format: {
        keyword: keyword,
        hex: hex,
        rgb: rgb,
        rgba: rgb,
        hsl: hsl,
        hsla: hsl
    },
    /* API */
    parse: (color) => {
        if (typeof color !== 'string')
            return color;
        const channels = hex.parse(color) || rgb.parse(color) || hsl.parse(color) || keyword.parse(color); // Color providers ordered with performance in mind
        if (channels)
            return channels;
        throw new Error(`Unsupported color format: "${color}"`);
    },
    stringify: (channels) => {
        // SASS returns a keyword if possible, but we avoid doing that as it's slower and doesn't really add any value
        if (!channels.changed && channels.color)
            return channels.color;
        if (channels.type.is(constants.TYPE.HSL) || channels.data.r === undefined) {
            return hsl.stringify(channels);
        }
        else if (channels.a < 1 || !Number.isInteger(channels.r) || !Number.isInteger(channels.g) || !Number.isInteger(channels.b)) {
            return rgb.stringify(channels);
        }
        else {
            return hex.stringify(channels);
        }
    }
};

module.exports = Color;
