const jwtSecret   = 'AjnjLhjxM'

const express           = require('express');
const express_graphql   = require('express-graphql');

const { buildSchema, printSchema } = require('graphql');
const expand = require('mm-graphql/expand')
const fs     = require('fs')
const uploadPath = `${__dirname}/public/images/`;
const upload  = require('multer')({ dest: uploadPath })


;(async () => {

    const {Savable, slice, getModels} = await require('./models.js')()
    const { jwtGQL, jwtCheck } = require('mm-graphql/jwt')

    const {anonSchema, anonResolvers} = require('./anon')({Savable, secret: jwtSecret})

    let schema = buildSchema(`
        type User {
             _id: String
             createdAt: String
             login: String
             nick : String
             avatar: Image
        }

        input UserInput {
             _id: String
             login: String
             nick : String
             avatar: ImageInput
        }

        type Image {
            _id: ID,
            text: String,
            url: String,
            originalFileName: String,
            userAvatar: User,
            good: Good
            category: Category
            owner: User
        }

        input ImageInput {
            _id: ID,
            text: String,
            userAvatar: UserInput,
            good: GoodInput
            category: CategoryInput
        }

        type Category {
            _id: ID,
            name: String!,
            goods: [Good]
            image: Image
        }

        input CategoryInput {
            _id: ID,
            name: String!,
            goods: [ID]
            image: ImageInput
        }

        type Good {
            _id: ID,
            name: String!,
            description: String
            price: Float
            orderGoods: [OrderGood]
            categories: [Category]
            images: [Image]
        }

        input GoodInput {
            _id: ID,
            name: String!,
            description: String
            price: Float
            categories: [CategoryInput]
            images: [ImageInput]
        }

        type OrderGood {
            _id: ID,
            price: Float,
            count: Float,
            good: Good,
            order: Order
        }

        input OrderGoodInput {
            _id: ID,
            count: Int!,
            good: [GoodInput],
            order: [OrderInput]
        }

        type Order {
            _id: ID
            total: Float
            orderGoods: [OrderGood]
        }

        input OrderInput {
            _id: ID
            orderGoods: [OrderGoodInput]
        }
    `);

    schema = expand(schema)
    console.log(printSchema(schema))

    const app = express();
    app.use(express.static('public'));
    app.use('/graphql', express_graphql(jwtGQL({anonSchema, anonResolvers, schema, createContext: getModels, graphiql: true, secret: jwtSecret})))


    app.post('/upload', upload.single('photo'), async (req, res, next) => {
        let decoded;
        console.log('wtf')
        if (decoded = jwtCheck(req, jwtSecret)){
            console.log('SOME UPLOAD', decoded, req.file)

            let {models: {Image }} = await getModels(decoded.sub)
            let image = await Image.fromFileData(req.file)
            res.end(JSON.stringify({_id: image._id, url: image.url}))
        }
        else {
            res.status(503).send('permission denied')
        }
    })

    app.use(express.static('public'));


    let socketPath = "/home/asmer/node_hosts/shop"
    app.listen(socketPath, () => {
        console.log('Express GraphQL Server Now Running On localhost:4000/graphql');
        fs.chmodSync(socketPath, '777');
    });
})()