import { error, isNumber, isArray, coordEach } from './helper';
import * as CRS from './crs/index';
/**
 * transform
 *
 * @param {geojson|position|string} input
 * @returns {geojson|position} output
 */
/* eslint-disable no-param-reassign */
export default function transform(input, crsFrom, crsTo) {
    /**
     * TODO:
     * if (condition) error(msg); -> assert(condition, msg);
     * the limitation of TS. https://github.com/Microsoft/TypeScript/issues/8655
     */
    if (!input)
        error('coordinate is required');
    if (!crsFrom)
        error('original coordinate system is required');
    if (!crsTo)
        error('target coordinate system is required');
    var from = CRS[crsFrom];
    if (!from)
        error('original coordinate system is invalid');
    if (crsFrom === crsTo)
        return input;
    var to = from.to[crsTo];
    if (!to)
        error('target coordinate system is invalid');
    var type = typeof input;
    if (type !== 'string' && type !== 'object')
        error('coordinate must be an geojson or an array of position');
    if (type === 'string') {
        try {
            input = JSON.parse(input);
        }
        catch (e) {
            error('input is not a legal JSON string');
        }
    }
    var isPosition = false;
    if (isArray(input)) {
        if (input.length < 2)
            error('position must be at 2 numbers long');
        if (!isNumber(input[0]) || !isNumber(input[1]))
            error('position must contain numbers');
        input = input.map(Number);
        isPosition = true;
    }
    var output = null;
    var convert = to;
    if (isPosition) {
        output = convert(input);
    }
    else {
        coordEach(input, function (coord) {
            var _a;
            _a = convert(coord), coord[0] = _a[0], coord[1] = _a[1];
        });
        output = input;
    }
    return output || '';
}
