const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
var socketIo = require('socket.io');
const dbsSrv = require('./core/dbService')
const crdSrv = require('./core/cardService');
var port = process.env.port || 1337;

const server = http.createServer(function (req, res) {
    var parsedUrl = url.parse(req.url);
    var pathname = `.${parsedUrl.pathname}`;
    var ext = path.parse(pathname).ext;
    var mimeType = {
        '.ico': 'image/x-icon',
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.json': 'application/json',
        '.css': 'text/css',
        '.png': 'image/png',
        '.jpg': 'image/jpeg',
        '.wav': 'audio/wav',
        '.mp3': 'audio/mpeg',
        '.svg': 'image/svg+xml',
        '.pdf': 'application/pdf',
        '.doc': 'application/msword',
        '.eot': 'appliaction/vnd.ms-fontobject',
        '.ttf': 'aplication/font-sfnt'
    };
    var parts = pathname.split("/");

    if (parts[1] === 'api') {
        switch (parts[2]) {
            case 'login':
                dbsSrv.systemAccess(req, res);
                break;
            case 'service':
                dbsSrv.systemService(req, res);
                break;
            case 'logout':
                dbsSrv.systemExit(req, res);
                break;
            default:
                res.statusCode = 500;
                res.end('Invalid Service Request');
                break;
        };
        return;
    };

    if (ext === '.svg') {
        crdSrv.getSvg(path.basename(pathname, '.svg'), res)
        return;
    }

    if (['.jpg', '.png'].indexOf(ext) > -1)
        pathname = './Images/' + path.basename(pathname);

    fs.exists(pathname, function (exist) {
        if (!exist || fs.statSync(pathname).isDirectory()) {
            pathname = "./public/index.html";
            ext = ".html";
        }

        fs.readFile(pathname, function (err, data) {
            if (err) {
                res.statusCode = 500;
                res.end(`Error getting the file: ${err}.`);
            } else {
                res.setHeader('Content-type', mimeType[ext] || 'text/plain');
                res.end(data);
            }
        });
    });

    returnGood = () => {
    }

    returnBad = (err) => {
    }
})

const io = socketIo(server)
io.sockets.on("connection", socket => {
    //  console.log(socket.id + " connected");
    var token = socket.handshake.query.token
    var game = socket.handshake.query.game
    socket.join(game);
    socket.on('reqPlayers', (data) => {
        data['soc'] = socket.id
        dbsSrv.systemAction(token, game, data, (err, resp) => {
            let plyr = JSON.parse(resp)
            io.sockets.in(game).emit('player', { players: plyr.players, live: plyr.live });
            io.sockets.in(game).emit('status', plyr.status)
            if (plyr.nxt)
                io.sockets.to(plyr.nxt.soc).emit('myturn', { coin: plyr.nxt.coin, avail: plyr.nxt.avail });
        });
    });
    socket.on('reqBoardCards', (data) => {
        dbsSrv.systemAction(token, game, data, (err, cards) => {
            let obj = JSON.parse(cards)
            obj.board.map((crd) => {
                crdSrv.BoardCard(crd, (err, resp) => {
                    socket.emit(game).emit('boardCard', resp);
                })
            })
        })
    })
    socket.on('reqDealtHand', (data) => {
        dbsSrv.systemAction(token, game, data, (err, cards) => {
            let obj = JSON.parse(cards)
            obj.hand.map((crd) => {
                crdSrv.DealtCard(crd, (err, resp) => {
                    socket.emit('dealtCard', resp);
                });
            })
        })
    });
    socket.on('reqNewGame', (data) => {
        dbsSrv.systemAction(token, game, data, (err, resp) => {
            let plyr = JSON.parse(resp)
            io.sockets.in(game).emit('status', plyr.status)
            if (plyr.status.typ === 2) {
                data['id'] = 'BRDCRD'
                dbsSrv.systemAction(token, game, data, (err, cards) => {
                    let obj = JSON.parse(cards)
                    obj.board.map((crd) => {
                        crdSrv.BoardCard(crd, (err, resp) => {
                            io.sockets.in(game).emit('boardCard', resp);
                        })
                    })
                })
                dbsSrv.nextPlayer(game, data, (err, next) => {
                    let nxt = JSON.parse(next)
                    io.sockets.to(nxt.soc).emit('myturn', { coin: nxt.coin, avail: nxt.avail });
                })
            }
        })
    })
    socket.on('PlayCard', (data) => {
        data.soc = socket.id
        dbsSrv.systemAction(token, game, data, (err, plyd) => {
            let obj = JSON.parse(plyd)
            obj.cards.map((crd) => {
                crdSrv.BoardCard(crd, (err, resp) => {
                    io.sockets.in(game).emit('boardCard', resp)
                });
            })
            io.sockets.in(game).emit('status', obj.status)
            // continue if game not over
            if (obj.status.typ === 0) {
                data['id'] = 'CRDNXT'
                dbsSrv.systemAction(token, game, data, (err, resp) => {
                    let crd = JSON.parse(resp)
                    crdSrv.DealtCard(crd, (err, image) => {
                        socket.emit('dealtCard', image);
                    });
                })
                // next player - check discards - update avail
                dbsSrv.nextPlayer(game, data, (err, next) => {
                    let nxt = JSON.parse(next)
                    nxt.dscrd.map((d) => {
                        crdSrv.DealtCard(d, (err, image) => {
                            io.sockets.to(nxt.soc).emit('dealtCard', image);
                        });
                    })
                    io.sockets.to(nxt.soc).emit('myturn', { coin: nxt.coin, avail: nxt.avail });
                })
            }
        });
    });
    socket.on('disconnect', () => {
        let data = { id: 'PLYERS', act: 0, soc: '' }
        dbsSrv.systemAction(token, game, data, (err, resp) => {
            let plyr = JSON.parse(resp)
            io.sockets.to(game).emit('player', { players: plyr.players, live: plyr.live });
            io.sockets.to(game).emit('status', plyr.status)
        });
    });
});
server.listen(port);
module.exports = server