import Tunnel from './Tunnel';
import { TunnelOptions } from './types';

interface LegacyCallback {
  (err: Error | null, tunnel?: Tunnel): void;
}

function localtunnel(port: number, options?: Omit<TunnelOptions, 'port'>, callback?: LegacyCallback): Promise<Tunnel>;
function localtunnel(options: TunnelOptions, callback?: LegacyCallback): Promise<Tunnel>;
function localtunnel(
  arg1: number | TunnelOptions,
  arg2?: LegacyCallback | Omit<TunnelOptions, 'port'>,
  arg3?: LegacyCallback
): Promise<Tunnel> {
  const options: TunnelOptions =
    typeof arg1 === 'object' ? arg1 : { ...(arg2 as Omit<TunnelOptions, 'port'>), port: arg1 };
  const callback: LegacyCallback | undefined = typeof arg1 === 'object' ? arg2 as LegacyCallback : arg3;

  const client = new Tunnel(options);

  if (callback) {
    client.open(err => (err ? callback(err) : callback(null, client)));
    return Promise.resolve(client);
  }

  return new Promise((resolve, reject) =>
    client.open(err => (err ? reject(err) : resolve(client)))
  );
}

export = localtunnel; 