const express = require('express'); //requires express module
const mongoose = require("mongoose");
const socket = require('socket.io'); //requires socket.io module
// Assuming you have a connection to the notification server
const notificationSocket = require('socket.io-client')('http://starapi.stararabgroup.com:3008');

const fs = require('fs');
var mysql = require('mysql');
var moment = require('moment');
const app = express();
var PORT = process.env.PORT || 1753;
const server = app.listen(PORT); //tells to host server on localhost:3000


//Playing variables:
app.use(express.static('public')); //show static files in 'public' directory

const User = require("./model/user.model");
const Payment = require("./model/payment.model");

const FruitTable = require("./model/fruit_table.model");
const FruitBid = require("./model/fruit_bid.model");
const JackpotWinning = require("./model/jackpotWinning.model");
const AppSetting = require("./model/appSetting.model");
const GameTransaction = require("./model/gameTransaction.model");

console.log('Server is running');
const io = socket(server, {
  cors: {
    origin: "*",
  }
});

mongoose.connect(
    `mongodb+srv://mohammad:FlvC33mQ3LZoBNHx@cluster0.jxnn5.mongodb.net/stararabchat_prod`,

    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    }
);

const db = mongoose.connection;

db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
    console.log("MONGO: successfully connected to db");
});


let result = 0;
let seat_1 = 0;
let seat_2 = 0;
let seat_3 = 0;
let seat_4 = 0;
let seat_5 = 0;
let seat_6 = 0;
let seat_7 = 0;
let seat_8 = 0;
let actual_seat_1 = 0;
let actual_seat_2 = 0;
let actual_seat_3 = 0;
let actual_seat_4 = 0;
let actual_seat_5 = 0;
let actual_seat_6 = 0;
let actual_seat_7 = 0;
let actual_seat_8 = 0;

let winratio = 40;

let customRes = false;
let count = Math.floor(Date.now()/1000)-((Math.floor(Math.floor(Date.now()/1000)/30))*30);
let status = count < 20 ? 1 : (count < 25 ? 2 : 3);
let counter = count < 20 ? 20-count : (count < 25 ?  5-(count-20) : 5-(count-25));
let sessionId = (Math.floor(Math.floor(Date.now()/1000)/30));

const resultarrs = [1,8,6,8,1,6,2,4,7,8,7,1,6,7,2,6,3,2,4,7,6,3,2,3,6,7,1,3,2,5,2,5,2,1,2,5,2,6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,6,1,5,2,5,6,2,1,3,5,2,5,2,5,3,2,5,2,5,3,6,1,7,6,3,4,6,2,3,4,3,1,5,7,4,2,4,5,4,5,3,4,6,4,3,2,8,7,6,7,6,1,2,3,6,3,4,7,6,3,2,6,4,1,4,1,2,4,2,1,4,7,1,4,1,4,1,4,3,2,3,5,4,5,3,2,4,2,6,7,5,2,3,4,2,7,4,3,1,7,1,8,3,5,1,5,6,7,4,6,1,6,5,4,2,4,7,6,5,7,3,4,2,1,3,7,1,7,4,3,2,4,5,3,1,4,3,6,3,4,1,4,2,3,2,4,2,1,3,5,4,5,6,5,1,4,5,3,2,5,6,8,2,3,5,6,2,6,1,3,1,6,1,6,2,1,2,1];
//const resultarrs = [1,8,1,8,1,8,8,1,8,8,8,2,3,4,5,1];
//Socket.io Connection------------------
io.on('connection', async (socket) => {
    
    let userUid = 0;
    let userId = 0;
    let userName = "";
    let userImage = "";
    
    console.log("New socket connection: " + socket.id)
    socket.on('join', function (data) {    
        socket.join(data);
        userUid = data;
        console.log("join: "+userUid);
        if (userUid == 1614626426 ) {
            console.log("banned join: "+userUid);
            socket.disconnect(true);
        }
    });
    let history = [];
    const jackpotBalance = await AppSetting.findOne({ name: 'new_fruit_jackpot'});
    if (jackpotBalance) {
        io.emit("jackpotChange", jackpotBalance.valueInt);
    }
    const fruitHistory = await FruitTable.aggregate([
        {
            $match: {
                session: { $lt: sessionId } // Replace with actual sessionId ObjectId
            }
        },
        {
            $sort: { session: -1 } // Sort by session in descending order
        },
        {
            $limit: 15 // Limit results to 15 documents
        },
        {
            $project: {
                result: 1, // Include only the "result" field
                session: 1 // Convert session ObjectId to string
            }
        }
    ]);

    for (const value of fruitHistory) {
        const index = fruitHistory.indexOf(value);
        history.push(value.result);
    }
    io.emit('history', {"history": history});
    
    socket.on('setResult', data => {
        if (status < 2) {
            result = data;
            customRes = true
            io.emit("setResultRes", result);
        }
    });
    
    let myBiddingSeat_1 = 0;
    let myBiddingSeat_2 = 0;
    let myBiddingSeat_3 = 0;
    let myBiddingSeat_4 = 0;
    let myBiddingSeat_5 = 0;
    let myBiddingSeat_6 = 0;
    let myBiddingSeat_7 = 0;
    let myBiddingSeat_8 = 0;
    let today = moment().startOf('day');
    const todayWinning = await Payment.aggregate([
        {
            $match: {
                userId: userUid, type: 756, isIncome: true, createdAt: {$gt: today.toDate()}
            }
        },
        {
            $group: {
                _id: "$userId",
                winBidAmt: {
                    $sum: "$coin"
                }
            }
        }
    ]);
    if (todayWinning.length > 0) {
        console.log('todayWinning',todayWinning);
        io.emit('myWinning', todayWinning[0].winBidAmt);
    }
    let oldOwnStatus = 0;
    let notBet = true;
    var t=setInterval(async function () {
        sessionId = (Math.floor(Math.floor(Date.now()/1000)/30));
        vsessionId = Math.floor((Math.floor(Date.now()/1000)-(Math.floor(Math.floor(Date.now()/1000)/86400)*86400))/30);
        count = Math.floor(Date.now()/1000)-((Math.floor(Math.floor(Date.now()/1000)/30))*30);
        const Ownstatus = count < 20 ? 1 : (count < 25 ? 2 : 3);
        if (oldOwnStatus != Ownstatus) {
            io.emit('roundChange', vsessionId);
        }
        if (oldOwnStatus != Ownstatus && Ownstatus == 1) {
            notBet = true;
            myBiddingSeat_1 = 0;
            myBiddingSeat_2 = 0;
            myBiddingSeat_3 = 0;
            myBiddingSeat_4 = 0;
            myBiddingSeat_5 = 0;
            myBiddingSeat_6 = 0;
            myBiddingSeat_7 = 0;
            myBiddingSeat_8 = 0;
            
            let today = moment().startOf('day');
            const todayWinning = await Payment.aggregate([
                {
                    $match: {
                        userId: userUid, isIncome: true, type: 756, createdAt: {$gt: today.toDate()}
                    }
                },
                {
                    $group: {
                        _id: "$userId",
                        winBidAmt: {
                            $sum: "$coin"
                        }
                    }
                }
            ]);
            if (todayWinning.length > 0) {
                io.emit('myWinning', todayWinning[0].winBidAmt);
            }
        }
//        if (oldOwnStatus != Ownstatus && Ownstatus == 2 && notBet) {
        if (Ownstatus == 1 && count > 15 && notBet) {
            notBet = false;
            console.log('status change', 'oldStatus', oldOwnStatus,'newStatus',Ownstatus);
            const totalBids = myBiddingSeat_1+myBiddingSeat_2+myBiddingSeat_3+myBiddingSeat_4+myBiddingSeat_5+myBiddingSeat_6+myBiddingSeat_7+myBiddingSeat_8;
            console.log('totalBids',totalBids);
            if (totalBids > 0) {
                console.log(totalBids);
                const user = await User.findOne({uid: userUid});
                if (user) {
                    if (user.balance >= totalBids) {
                        await User.updateOne({uid: userUid},{ $inc: { balance: -totalBids } });
                        const paymentBidding = new Payment();
                        paymentBidding.userId = userUid;
                        paymentBidding.coin = totalBids;
                        paymentBidding.type = 756
                        paymentBidding.isIncome = false;
                        paymentBidding.date = new Date().toLocaleString();
                        paymentBidding.save();

                        const gameTransaction = new GameTransaction();
                        gameTransaction.session = sessionId
                        gameTransaction.uid = userUid;
                        gameTransaction.name = userName;
                        gameTransaction.gameId = 4;
                        gameTransaction.coins = -totalBids;
                        gameTransaction.type = 0;
                        gameTransaction.save();
                        
                        const companyShare = (totalBids)*0.2;
                        const rotationShare = (totalBids)*0.8;
                        const companyBalance = await AppSetting.findOne({ name: 'newFruit_company'});
                        companyBalance.valueInt = companyBalance.valueInt+companyShare;
                        await companyBalance.save();
                    }
                    if (myBiddingSeat_1 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_1;
                        fruitBid.seat = 1;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 1 bid added for '+userName+' Amount: '+myBiddingSeat_1)
                    }
                    if (myBiddingSeat_2 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_2;
                        fruitBid.seat = 2;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 2 bid added for '+userName+' Amount: '+myBiddingSeat_2)
                    }
                    if (myBiddingSeat_3 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_3;
                        fruitBid.seat = 3;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 3 bid added for '+userName+' Amount: '+myBiddingSeat_3)
                    }
                    if (myBiddingSeat_4 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_4;
                        fruitBid.seat = 4;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 4 bid added for '+userName+' Amount: '+myBiddingSeat_4)
                    }
                    if (myBiddingSeat_5 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_5;
                        fruitBid.seat = 5;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 5 bid added for '+userName+' Amount: '+myBiddingSeat_5)
                    }
                    if (myBiddingSeat_6 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_6;
                        fruitBid.seat = 6;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 6 bid added for '+userName+' Amount: '+myBiddingSeat_6)
                    }
                    if (myBiddingSeat_7 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_7;
                        fruitBid.seat = 7;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 7 bid added for '+userName+' Amount: '+myBiddingSeat_7)
                    }
                    if (myBiddingSeat_8 > 0) {
                        const fruitBid = new FruitBid();
                        fruitBid.uid = userUid;
                        fruitBid.name = userName;
                        fruitBid.image = userImage;
                        fruitBid.session = sessionId;
                        fruitBid.vsession = vsessionId;
                        fruitBid.amount = myBiddingSeat_8;
                        fruitBid.seat = 8;
                        fruitBid.save();
                        console.log(Math.floor(Date.now() / 1000),' seat 8 bid added for '+userName+' Amount: '+myBiddingSeat_8)
                    }
        
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_1: myBiddingSeat_1 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_1: myBiddingSeat_1 } })
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_2: myBiddingSeat_2 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_2: myBiddingSeat_2 } })
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_3: myBiddingSeat_3 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_3: myBiddingSeat_3 } })
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_4: myBiddingSeat_4 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_4: myBiddingSeat_4 } })
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_5: myBiddingSeat_5 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_5: myBiddingSeat_5 } })
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_6: myBiddingSeat_6 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_6: myBiddingSeat_6 } })
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_7: myBiddingSeat_7 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_7: myBiddingSeat_7 } })
                    await FruitTable.updateOne({session: sessionId},{ $inc: { seat_8: myBiddingSeat_8 } });
                    console.log('updateOne', {session: sessionId},{ $inc: { seat_8: myBiddingSeat_8 } })
                }
            }
        }
        oldOwnStatus = Ownstatus;
    },1000);
    socket.on("disconnect", async () => {
        myBiddingSeat_1 = 0;
        myBiddingSeat_2 = 0;
        myBiddingSeat_3 = 0;
        myBiddingSeat_4 = 0;
        myBiddingSeat_5 = 0;
        myBiddingSeat_6 = 0;
        myBiddingSeat_7 = 0;
        myBiddingSeat_8 = 0;
    });
    socket.on('bid', async (data) => {
        if (status == 1) {
            const response = JSON.parse(data);
            const bidder = response.uid;
            const bidderId = response.id;
            const amount = response.selectedBidding;
            const seat = response.seat;
            const user = await User.findOne({uid: bidder});
            if (user) {
                if (user.balance >= amount) {
                    userUid = user.uid
                    userName = user.fullname
                    userImage = user.image
                    if (seat == 1) {
                        seat_1 = seat_1+amount
                        actual_seat_1 = actual_seat_1+amount
                        myBiddingSeat_1 = myBiddingSeat_1+amount
                    }
                    else if (seat == 2) {
                        seat_2 = seat_2+amount
                        actual_seat_2 = actual_seat_2+amount
                        myBiddingSeat_2 = myBiddingSeat_2+amount
                    }
                    else if (seat == 3) {
                        seat_3 = seat_3+amount
                        actual_seat_3 = actual_seat_3+amount
                        myBiddingSeat_3 = myBiddingSeat_3+amount
                    }
                    else if (seat == 4) {
                        seat_4 = seat_4+amount
                        actual_seat_4 = actual_seat_4+amount
                        myBiddingSeat_4 = myBiddingSeat_4+amount
                    }
                    else if (seat == 5) {
                        seat_5 = seat_5+amount
                        actual_seat_5 = actual_seat_5+amount
                        myBiddingSeat_5 = myBiddingSeat_5+amount
                    }
                    else if (seat == 6) {
                        seat_6 = seat_6+amount
                        actual_seat_6 = actual_seat_6+amount
                        myBiddingSeat_6 = myBiddingSeat_6+amount
                    }
                    else if (seat == 7) {
                        seat_7 = seat_7+amount
                        actual_seat_7 = actual_seat_7+amount
                        myBiddingSeat_7 = myBiddingSeat_7+amount
                    }
                    else if (seat == 8) {
                        seat_8 = seat_8+amount
                        actual_seat_8 = actual_seat_8+amount
                        myBiddingSeat_8 = myBiddingSeat_8+amount
                    }
                    console.log(Math.floor(Date.now() / 1000),data)
                    console.log(bidder);
                    console.log(bidderId);
                    console.log(amount);
                    console.log(seat);
                    io.emit('sinbid', {"seat": seat,"amount": amount});
                    io.emit('bidding', {"bidder": 0,"seat_1": seat_1,"seat_2": seat_2,"seat_3": seat_3,"seat_4": seat_4,"seat_5": seat_5,"seat_6": seat_6,"seat_7": seat_7,"seat_8": seat_8,"actual_seat_1": actual_seat_1,"actual_seat_2": actual_seat_2,"actual_seat_3": actual_seat_3,"actual_seat_4": actual_seat_4,"actual_seat_5": actual_seat_5,"actual_seat_6": actual_seat_6,"actual_seat_7": actual_seat_7,"actual_seat_8": actual_seat_8});
                };
            };
        }
    })
})

var t=setInterval(async function () {
    const oldStatus = status;
    sessionId = (Math.floor(Math.floor(Date.now()/1000)/30));
    vsessionId = (Math.floor(Math.floor(Date.now()/1000)-(Math.floor(Math.floor(Date.now()/1000)/86400))/30));
    count = Math.floor(Date.now()/1000)-((Math.floor(Math.floor(Date.now()/1000)/30))*30);
    status = count < 20 ? 1 : (count < 25 ? 2 : 3);
    counter = count < 20 ? 20-count : (count < 25 ?  5-(count-20) : 5-(count-25));
    if (status == 1) {
        seat = Math.floor(1 + Math.random()*(8 - 1 + 1));
        amount = Math.floor(1 + Math.random()*(100 - 1 + 1))*10;
        if (seat == 1) {
            seat_1 = seat_1+amount
        }
        else if (seat == 2) {
            seat_2 = seat_2+amount
        }
        else if (seat == 3) {
            seat_3 = seat_3+amount
        }
        else if (seat == 4) {
            seat_4 = seat_4+amount
        }
        else if (seat == 5) {
            seat_5 = seat_5+amount
        }
        else if (seat == 6) {
            seat_6 = seat_6+amount
        }
        else if (seat == 7) {
            seat_7 = seat_7+amount
        }
        else if (seat == 8) {
            seat_8 = seat_8+amount
        }
        io.emit('sinbid', {"seat": seat,"amount": amount});
        io.emit('bidding', {"bidder": 1,"seat_1": seat_1,"seat_2": seat_2,"seat_3": seat_3,"seat_4": seat_4,"seat_5": seat_5,"seat_6": seat_6,"seat_7": seat_7,"seat_8": seat_8,"actual_seat_1": actual_seat_1,"actual_seat_2": actual_seat_2,"actual_seat_3": actual_seat_3,"actual_seat_4": actual_seat_4,"actual_seat_5": actual_seat_5,"actual_seat_6": actual_seat_6,"actual_seat_7": actual_seat_7,"actual_seat_8": actual_seat_8});
    }
    if (oldStatus == 3 && status == 1) {
        customRes = false
        result = 0;
        seat_1 = 0;
        seat_2 = 0;
        seat_3 = 0;
        seat_4 = 0;
        seat_5 = 0;
        seat_6 = 0;
        seat_7 = 0;
        seat_8 = 0;
        actual_seat_1 = 0;
        actual_seat_2 = 0;
        actual_seat_3 = 0;
        actual_seat_4 = 0;
        actual_seat_5 = 0;
        actual_seat_6 = 0;
        actual_seat_7 = 0;
        actual_seat_8 = 0;
        io.emit('bidding', {"bidder": 0,"seat_1": seat_1,"seat_2": seat_2,"seat_3": seat_3,"seat_4": seat_4,"seat_5": seat_5,"seat_6": seat_6,"seat_7": seat_7,"seat_8": seat_8,"actual_seat_1": actual_seat_1,"actual_seat_2": actual_seat_2,"actual_seat_3": actual_seat_3,"actual_seat_4": actual_seat_4,"actual_seat_5": actual_seat_5,"actual_seat_6": actual_seat_6,"actual_seat_7": actual_seat_7,"actual_seat_8": actual_seat_8});
        io.emit('bidding', {"bidder": 1,"seat_1": seat_1,"seat_2": seat_2,"seat_3": seat_3,"seat_4": seat_4,"seat_5": seat_5,"seat_6": seat_6,"seat_7": seat_7,"seat_8": seat_8,"actual_seat_1": actual_seat_1,"actual_seat_2": actual_seat_2,"actual_seat_3": actual_seat_3,"actual_seat_4": actual_seat_4,"actual_seat_5": actual_seat_5,"actual_seat_6": actual_seat_6,"actual_seat_7": actual_seat_7,"actual_seat_8": actual_seat_8});
        const newFruitTable = new FruitTable();
        newFruitTable.session = sessionId;
        newFruitTable.result = 1;
        newFruitTable.seat_1 = 0;
        newFruitTable.seat_2 = 0;
        newFruitTable.seat_3 = 0;
        await newFruitTable.save();
        
        let history = [];
        const fruitHistory = await FruitTable.aggregate([
            {
                $match: {
                    session: { $lt: sessionId } // Replace with actual sessionId ObjectId
                }
            },
            {
                $sort: { session: -1 } // Sort by session in descending order
            },
            {
                $limit: 15 // Limit results to 15 documents
            },
            {
                $project: {
                    result: 1, // Include only the "result" field
                    session: 1 // Convert session ObjectId to string
                }
            }
        ]);

        for (const value of fruitHistory) {
            const index = fruitHistory.indexOf(value);
            history.push(value.result);
        }
        io.emit('history', {"history": history});
        if (result == 0) {
            result = Math.floor(1 + Math.random()*(8 - 1 + 1));
            io.emit("setResultRes", result);
        }
        
        const jackpotBalance = await AppSetting.findOne({ name: 'new_fruit_jackpot'});
        if (jackpotBalance) {
            io.emit("jackpotChange", jackpotBalance.valueInt);
        }
    }
    if (oldStatus == 1 && status == 2) {
        let top3 = [];
        const fruitTopBidding = await FruitBid.aggregate([
            {
                $match: {
                    session: sessionId,
                    seat: result
                }
            },
            {
                $group: {
                    _id: "$uid",
                    uid: { $first:"$uid" },
                    name: { $first:"$name" },
                    image: { $first:"$image" },
                    bidAmt: { $sum: "$amount" },
                    winBidAmt: {
                        $sum: {
                            $cond: {
                                if: { $and: [ { $eq: [ "$seat", result ] } ] },
                                then: "$amount",
                                else: 0
                            }
                        }
                    }
                }
            },
            {
                $sort: { winBidAmt: -1 }
            },
            {
                $limit: 3
            }
        ]);
        console.log('fruitTopBidding');
        console.log(JSON.stringify([
            {
                $match: {
                    session: sessionId,
                    seat: result
                }
            },
            {
                $group: {
                    _id: "$uid",
                    uid: { $first:"$uid" },
                    name: { $first:"$name" },
                    bidAmt: { $sum: "$amount" },
                    winBidAmt: {
                        $sum: {
                            $cond: {
                                if: { $and: [ { $eq: [ "$seat", result ] } ] },
                                then: "$amount",
                                else: 0
                            }
                        }
                    }
                }
            },
            {
                $sort: { winBidAmt: -1 }
            },
            {
                $limit: 3
            }
        ]));
        console.log(fruitTopBidding)
        for (const value of fruitTopBidding) {
            const index = fruitTopBidding.indexOf(value);
            const factors = [5, 5, 5, 5, 10, 15, 25, 40];
            top3.push({uid: value.uid, image: value.image, name: value.name, bid: value.bidAmt, win: (value.winBidAmt*factors[result-1])-Math.floor((value.winBidAmt*factors[result-1])/25)});
        }
        if (top3.length === 0) {
            top3.push({uid: 0, name: '', image: '', bid: 0, win: 0});
            top3.push({uid: 0, name: '', image: '', bid: 0, win: 0});
            top3.push({uid: 0, name: '', image: '', bid: 0, win: 0});
        }
        else if (top3.length === 1) {
            top3.push({uid: 0, name: '', image: '', bid: 0, win: 0});
            top3.push({uid: 0, name: '', image: '', bid: 0, win: 0});
        }
        else if (top3.length === 2) {
            top3.push({uid: 0, name: '', image: '', bid: 0, win: 0});
        }
        console.log('result', {result: result, highscores: top3});
        io.emit('result', {result: result, highscores: top3});
        let totalbids = actual_seat_1+actual_seat_2+actual_seat_3+actual_seat_4+actual_seat_5+actual_seat_6+actual_seat_7+actual_seat_8;
        let totalwin = 0;
        if (result == 1) {
            totalwin = actual_seat_1;
        } else if (result == 2) {
            totalwin = actual_seat_2;
        } else if (result == 3) {
            totalwin = actual_seat_3;
        } else if (result == 4) {
            totalwin = actual_seat_4;
        } else if (result == 5) {
            totalwin = actual_seat_5;
        } else if (result == 6) {
            totalwin = actual_seat_6;
        } else if (result == 7) {
            totalwin = actual_seat_7;
        } else if (result == 8) {
            totalwin = actual_seat_8;
        }
        const factors = [5, 5, 5, 5, 10, 15, 25, 40];
        totalwin = (totalwin*factors[result-1])-Math.floor((totalwin*factors[result-1])/25);
        const jackpotBalance = await AppSetting.findOne({ name: 'new_fruit_jackpot'});
        if (totalbids-totalwin > 0) {
            jackpotBalance.valueInt = jackpotBalance.valueInt+Math.floor((totalbids-totalwin)/10);
            await jackpotBalance.save();
        }
    }
    if (oldStatus == 2 && status == 3) {
        console.log(Date.now(),"state result");

        await FruitTable.updateOne({session: sessionId},{ $set: { result: result } });

        const fruitBidding = await FruitBid.aggregate([
            {
                $match: {
                    session: sessionId
                }
            },
            {
                $group: {
                    _id: "$uid",
                    uid: { $first:"$uid" },
                    name: { $first:"$name" },
                    image: { $first:"$image" },
                    bidAmt: { $sum: "$amount" },
                    winBidAmt: {
                        $sum: {
                            $cond: {
                                if: { $and: [ { $eq: [ "$seat", result ] } ] },
                                then: "$amount",
                                else: 0
                            }
                        }
                    }
                }
            },
            {
                $sort: {bidAmt: -1}
            }
        ]);
        
        let totalbids = actual_seat_1+actual_seat_2+actual_seat_3+actual_seat_4+actual_seat_5+actual_seat_6+actual_seat_7+actual_seat_8;
        let jackpotAmt = 0;
        let jackpotTop1Bet = 0;
        let jackpotTop1Name = "";
        let jackpotTop1Avatar = "";
        let jackpotTop2Bet = 0;
        let jackpotTop2Name = "";
        let jackpotTop2Avatar = "";
        let jackpotTop3Bet = 0;
        let jackpotTop3Name = "";
        let jackpotTop3Avatar = "";
        
        if (result == 8) {
            jackpotAmt = totalbids+Math.floor(Math.random()*((totalbids/10*-1) - (totalbids/10) + (totalbids/10)));
            const jackpotBalance = await AppSetting.findOne({ name: 'new_fruit_jackpot'});
            if (jackpotAmt > jackpotBalance.valueInt) {
                jackpotAmt = jackpotBalance.valueInt-10;
            }
            jackpotBalance.valueInt = jackpotBalance.valueInt-jackpotAmt;
            jackpotBalance.save();
        }
        for (const value of fruitBidding) {
            console.log('biddings result',value)
            const index = fruitBidding.indexOf(value);
            if (result == 8 && jackpotAmt > 0) {
                let mypercentage = value.bidAmt/(totalbids/100);
                let myReward = Math.floor((jackpotAmt/100)*mypercentage);
                if (index == 0) {
                    jackpotTop1Bet = myReward;
                    jackpotTop1Name = value.name;
                    jackpotTop1Avatar = value.image;
                }
                if (index == 1) {
                    jackpotTop2Bet = myReward;
                    jackpotTop2Name = value.name;
                    jackpotTop2Avatar = value.image;
                }
                if (index == 2) {
                    jackpotTop3Bet = myReward;
                    jackpotTop3Name = value.name;
                    jackpotTop3Avatar = value.image;
                }
                const jackpotWinning = new JackpotWinning();
                jackpotWinning.session = sessionId;
                jackpotWinning.vsession = vsessionId;
                jackpotWinning.userId = value.uid;
                jackpotWinning.name = value.name;
                jackpotWinning.avatar = value.image;
                jackpotWinning.reward = myReward;
                jackpotWinning.contribution = mypercentage;
                jackpotWinning.rank = index;
                jackpotWinning.save();
                await User.updateOne({uid: value.uid},{ $inc: { balance: myReward } });
                const paymentWinning = new Payment();
                paymentWinning.userId = value.uid;
                paymentWinning.coin = myReward;
                paymentWinning.type = 756
                paymentWinning.isIncome = true;
                paymentWinning.extra_data = "Jackpot Win";
                paymentWinning.date = new Date().toLocaleString();
                paymentWinning.save();
                const gameTransaction = new GameTransaction();
                gameTransaction.session = sessionId
                gameTransaction.uid = value.uid;
                gameTransaction.name = value.name;
                gameTransaction.gameId = 4;
                gameTransaction.coins = winning;
                gameTransaction.type = 2;
                gameTransaction.save();
                //const premiumMessage = value.name+" won "+winning+" Coins! in JackPot!!";
                //notificationSocket.emit('game_notification', {gameType: 2,message: premiumMessage});
            }
            const factors = [5, 5, 5, 5, 10, 15, 25, 40];
            const winning = (value.winBidAmt*factors[result-1])-Math.floor((value.winBidAmt*factors[result-1])/25);
            io.emit('myresult', {uid: value.uid, bid: value.bidAmt, win: winning});
            
            if (winning > 0) {
                await User.updateOne({uid: value.uid},{ $inc: { balance: winning } });
                const paymentWinning = new Payment();
                paymentWinning.userId = value.uid;
                paymentWinning.coin = winning;
                paymentWinning.type = 756
                paymentWinning.isIncome = true;
                paymentWinning.date = new Date().toLocaleString();
                paymentWinning.save();
                const gameTransaction = new GameTransaction();
                gameTransaction.session = sessionId
                gameTransaction.uid = value.uid;
                gameTransaction.name = value.name;
                gameTransaction.gameId = 4;
                gameTransaction.coins = winning;
                gameTransaction.type = 1;
                gameTransaction.save();
                if (winning > 5000) {
                const premiumMessage = value.name+" won "+winning+" Coins!";
                notificationSocket.emit('game_notification', {gameType: 2,message: premiumMessage});
                }
            }
        }
        if (result == 8 && jackpotAmt > 0) {
            io.emit("jackpotOpen",{top1Bet: jackpotTop1Bet,top1Name: jackpotTop1Name,top1Avatar: jackpotTop1Avatar,top2Bet: jackpotTop2Bet,top2Name: jackpotTop2Name,top2Avatar: jackpotTop2Avatar,top3Bet: jackpotTop3Bet,top3Name: jackpotTop3Name,top3Avatar: jackpotTop3Avatar})
        }
    }
    io.emit('counter', counter);
    if (counter <= 5 && status != 3) {
        if (status == 1 && !customRes) {
            customRes = true;
            console.log(" round Roll: "+sessionId % resultarrs.length);
            //result = resultarrs[sessionId % resultarrs.length];
            //io.emit("setResultRes", result);
            const rotationBalance = await AppSetting.findOne({ name: 'newFruit_rotation'});
            const totalBids = actual_seat_1+actual_seat_2+actual_seat_3+actual_seat_4+actual_seat_5+actual_seat_6+actual_seat_7+actual_seat_8;
            let rotationShare = Math.floor(totalBids*0.8);
            console.log('rotationShare',rotationShare);
            let maxReward = Math.floor(rotationShare * 8);
            rotationBalance.valueInt = rotationBalance.valueInt+rotationShare;
            if (maxReward > rotationBalance.valueInt) {
                maxReward = rotationBalance.valueInt;
            }
            console.log('rotationBalance',rotationBalance.valueInt);
            console.log('maxReward',maxReward);
            const array = [actual_seat_1*2,actual_seat_2*4,actual_seat_3*6,actual_seat_4*14,actual_seat_5*28,actual_seat_6*50,actual_seat_7*50,actual_seat_8*50];
            let suitvals = [];
            await array.forEach((item, index, arr) => {
                console.log(item,index,arr)
                if (item < maxReward) {
                    suitvals.push(index+1);
                }
            });
            console.log('suitvals',suitvals);
            if (suitvals.length > 0) {
                result = suitvals[Math.floor(Math.random()*(suitvals.length))];
                console.log('final result suit', result);
                io.emit("setResultRes", result);
            }
            else {
                let largest = array[0];
                let largestIndex = 1;
                await array.forEach((item, index, arr) => {
                    console.log(item,index,arr)
                    if (item < largest) {
                        largest = item;
                        largestIndex = index+1;
                        result = largestIndex;;
                    }
                });
                console.log('final result random', result);
                io.emit("setResultRes", result)
            }
            rotationBalance.valueInt = rotationBalance.valueInt-array[result-1];
            console.log('add reward',rotationBalance.valueInt)
            await rotationBalance.save();
        }
        io.emit('status', 2);
    }
    else {
        io.emit('status', status);
    }
},1000);