import { t } from '../core/localizer';
import { actionStraightenNodes } from '../actions/straighten_nodes';
import { actionStraightenWay } from '../actions/straighten_way';
import { behaviorOperation } from '../behavior/operation';
import { geoExtent } from '../geo';
import { utilArrayDifference, utilGetAllNodes } from '../util/index';


export function operationStraighten(context, selectedIDs) {
    var wayIDs = selectedIDs.filter(function(id) { return id.charAt(0) === 'w'; });
    var nodeIDs = selectedIDs.filter(function(id) { return id.charAt(0) === 'n'; });

    var nodes = utilGetAllNodes(selectedIDs, context.graph());
    var coords = nodes.map(function(n) { return n.loc; });
    var extent = nodes.reduce(function(extent, node) {
        return extent.extend(node.extent(context.graph()));
    }, geoExtent());
    var action = chooseAction();
    var geometry;


    function chooseAction() {
        // straighten selected nodes
        if (wayIDs.length === 0 && nodeIDs.length > 2) {
            geometry = 'points';
            return actionStraightenNodes(nodeIDs, context.projection);

        // straighten selected ways (possibly between range of 2 selected nodes)
        } else if (wayIDs.length > 0 && (nodeIDs.length === 0 || nodeIDs.length === 2)) {
            var startNodeIDs = [];
            var endNodeIDs = [];

            for (var i = 0; i < selectedIDs.length; i++) {
                var entity = context.entity(selectedIDs[i]);
                if (entity.type === 'node') {
                    continue;
                } else if (entity.type !== 'way' || entity.isClosed()) {
                    return null;  // exit early, can't straighten these
                }

                startNodeIDs.push(entity.first());
                endNodeIDs.push(entity.last());
            }

            // Remove duplicate end/startNodeIDs (duplicate nodes cannot be at the line end)
            startNodeIDs = startNodeIDs.filter(function(n) {
                return startNodeIDs.indexOf(n) === startNodeIDs.lastIndexOf(n);
            });
            endNodeIDs = endNodeIDs.filter(function(n) {
                return endNodeIDs.indexOf(n) === endNodeIDs.lastIndexOf(n);
            });

            // Ensure all ways are connected (i.e. only 2 unique endpoints/startpoints)
            if (utilArrayDifference(startNodeIDs, endNodeIDs).length +
                utilArrayDifference(endNodeIDs, startNodeIDs).length !== 2) return null;

            // Ensure path contains at least 3 unique nodes
            var wayNodeIDs = utilGetAllNodes(wayIDs, context.graph())
                .map(function(node) { return node.id; });
            if (wayNodeIDs.length <= 2) return null;

            // If range of 2 selected nodes is supplied, ensure nodes lie on the selected path
            if (nodeIDs.length === 2 && (
                wayNodeIDs.indexOf(nodeIDs[0]) === -1 || wayNodeIDs.indexOf(nodeIDs[1]) === -1
            )) return null;

            geometry = wayIDs.length === 1 ? 'line' : 'lines';
            return actionStraightenWay(selectedIDs, context.projection);
        }

        return null;
    }


    function operation() {
        if (!action) return;

        context.perform(action, operation.annotation());

        window.setTimeout(function() {
            context.validator().validate();
        }, 300);  // after any transition
    }


    operation.available = function() {
        return Boolean(action);
    };


    operation.disabled = function() {
        var reason = action.disabled(context.graph());
        if (reason) {
            return reason;
        } else if (extent.percentContainedIn(context.map().extent()) < 0.8) {
            return 'too_large.' + ((wayIDs.length ? wayIDs : nodeIDs).length === 1 ? 'single' : 'multiple');
        } else if (someMissing()) {
            return 'not_downloaded';
        } else if (selectedIDs.some(context.hasHiddenConnections)) {
            return 'connected_to_hidden';
        }

        return false;


        function someMissing() {
            if (context.inIntro()) return false;
            var osm = context.connection();
            if (osm) {
                var missing = coords.filter(function(loc) { return !osm.isDataLoaded(loc); });
                if (missing.length) {
                    missing.forEach(function(loc) { context.loadTileAtLoc(loc); });
                    return true;
                }
            }
            return false;
        }
    };


    operation.tooltip = function() {
        var disable = operation.disabled();
        return disable ?
            t('operations.straighten.' + disable) :
            t('operations.straighten.description.' + geometry);
    };


    operation.annotation = function() {
        return t('operations.straighten.annotation.' + geometry);
    };


    operation.id = 'straighten';
    operation.keys = [t('operations.straighten.key')];
    operation.title = t('operations.straighten.title');
    operation.behavior = behaviorOperation(context).which(operation);

    return operation;
}

@@ -2961,32 +2961,386 @@
 ) return null;%0A%0A
+            if (nodeIDs.length) %7B%0A                // If we're only straightenting between two points, we only need that extent visible%0A                extent = utilGetAllNodes(nodeIDs, context.graph()).reduce(function(extent, node) %7B%0A                    return extent.extend(node.extent(context.graph()));%0A                %7D, geoExtent());%0A            %7D%0A%0A
             geom

Allow straightening a selected line between two points if the two points are visible, regardless of how long the line is