/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
#include <iostream>
#include <memory>
#include <thrift/lib/cpp2/server/ThriftServer.h>

#include <thrift/tutorial/cpp/async/fetcher/FetcherHandler.h>

using namespace std;
using namespace folly;
using namespace apache::thrift;
using namespace apache::thrift::tutorial::fetcher;

void usage(ostream& os, const char* progname) {
  os << "Usage: " << progname << " [PORT]" << endl;
}

int main(int argc, char* argv[]) {
  // If an argument was supplied, it is the port number to listen on
  unsigned short port = 12345;
  if (argc == 2) {
    char* endptr;
    long val = strtol(argv[1], &endptr, 0);
    if (endptr == argv[1] || *endptr != '\0') {
      cerr << "error: port number must be an integer" << endl;
      return 1;
    }
    if (val < 0 || val > 0xffff) {
      cerr << "error: illegal port number " << val << endl;
      return 1;
    }
    port = val;
  } else if (argc > 2) {
    usage(cerr, argv[0]);
    cerr << "error: too many arguments" << endl;
    return 1;
  }

  ThriftServer server;
  server.setInterface(make_shared<FetcherHandler>());
  server.setPort(port);

  // Serve requests
  cout << "Serving requests on port " << port << "..." << endl;
  server.serve();

  return 0;
}
