import express from 'express';
import graphqlHTTP from 'express-graphql';
import OpticsAgent from 'optics-agent';
import { createServer } from 'http';
import { execute, subscribe } from 'graphql';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
import bodyParser from 'body-parser';

import schema from './schema';
import loaders from './Loaders';

const app = express();
const PORT = 3000;

OpticsAgent.instrumentSchema(schema);
app.use(OpticsAgent.middleware());

app.use(bodyParser.json());

// app.use(graphqlHTTP(req => ({
//   context: {
//     loaders,
//     opticsContext: OpticsAgent.context(req),
//   },
//   graphiql: true,
//   schema,
// })));

app.use('/graphql', graphqlExpress({
  context: {
    loaders,
    // opticsContext: OpticsAgent.context(req),
  },
  schema,
}));

app.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
  subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`,
}));

const server = createServer(app);

server.listen(PORT, () => {
  new SubscriptionServer({
    execute,
    subscribe,
    schema,
    onConnect: () => console.log('new client connected'),
  }, {
    server,
    path: '/subscriptions',
  });
});

console.log(`Middle running at http://localhost:${PORT}`);
