const express = require('express');


const path = require('path');

const socket = require('socket.io');
const http = require("http");
const session = require('express-session');
const bodyParser = require('body-parser');
//const redis = require('redis');
const escape_game = require('./escape_game');
const cors = require('cors');
const { pool } = require('./pool');
const { createUsersTable } = require('./database');

const APILocation = '/API';

(async ()=>{
  await createUsersTable()
})

const directionLink = (text, link) => {
  return `<a href=${link}>${text}</a>`;
}

var listToVictory = null;

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))


//Configure session middleware
app.use(session({
  secret: '***',
  // create new redis store.
  //store: new redisStore({ host: '127.0.0.1', port: 6379,client: RedisClient}),
  saveUninitialized: false,
  resave: false
}));






app.use(cors());



app.use((req, res, next) => {
  if (req.session.username) {
    // Oturum açılmışsa
    const sessionKey = `sess:${req.sessionID}`;

    console.log(sessionKey);
  }
  // Sonraki işlemi tetikle
  next();
});


app.use((req, res, next) => {
  if (req.session.username) {
    // Eğer kullanıcı oturum açmışsa, işlemi devam ettir
    next();
  } else {
    // Kullanıcı oturum açmamışsa, hata döndür
    if (req.url !== '/' && req.url !== '/API/login' && req.url !== '/API/getLevel' && req.url !== '/signIn' && !req.url.match(/library/m) && !req.url.match(/login/m) && !req.url.match(/signIn/m) && !req.url.match(/assets\/font/m) && !req.url.match(/sounds\/soundtracks\//m)) {
      // res.status(401).send('Unauthorized' + req.url);
      next()
    } else {

      next()
    }



  }
});

app.post(APILocation + '/update', async (req, res) => {
  const { update, feature, username } = req.body;
  try {
    const targetUserInfo = await QueryCode(
      'SELECT `username`, `id` FROM `users` WHERE `username`=?',
      [username]
    );

    if (targetUserInfo.length > 0) {
      const targetUserId = targetUserInfo[0].id;
      const targetUserUpdated = await QueryCode(
        `UPDATE \`users\` SET \`${feature}\`=? WHERE \`id\`=?`,
        [update, targetUserId]
      );
      res.status(200).json({ message: 'User information updated successfully' });
    } else {
      res.status(404).json({ error: 'User not found' });
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});




app.post(APILocation + '/signIn', async (req, res) => {
  const { username, menuname, password } = req.body;
console.log(username);
  try {
    const UserLoginInfo = await controllUserName(username);
    console.log(UserLoginInfo);




    if ((UserLoginInfo && UserLoginInfo.length == 0)) {
      if ((username).length > 2 && (password).length > 2 && (menuname).length > 0) {

        await defaultAddUser(username, password, menuname);
        req.session.username = username; // Yeni eklenen kullanıcı bilgileri
        req.session.password = password;
        // res.send(directionLink('Success Please Click', '/index.html'));
        res.status(200).send({ message: 'success' });
      } else {
 
        req.session.username = username; // Yeni eklenen kullanıcı bilgileri
        req.session.password = password;
        // res.send(directionLink('Success Please Click', '/index.html'));
        res.status(403).send({ message: 'your password is so weak' });
      }

    }
    else {


      // res.send(directionLink('Sorry, the username you have chosen is already taken', '/signIn.html'));
      res.status(409).send({ message: 'unsuccess' });
    }
  } catch (err) {
    console.error('Error: ', err);
    res.status(500).send({ message: 'Internal Server Error' });
  }
  res.end();
});



app.post(APILocation + '/exit', async (req, res, next) => {
  req.session.destroy(err => {

    if (err) {
      console.error('Error', err)
      return;
    }
    res.end();
  })

  next();
})


app.post(APILocation + '/login', async (req, res) => {
  const { username, password } = req.body;
  try {
    const UserLoginInfo = await controllUser(username, password);
    if (!UserLoginInfo || UserLoginInfo.length < 1) {
      res.status(409).send({ message: 'Your info is false' });
    } else {
      req.session.username = UserLoginInfo[0].username;
      req.session.password = UserLoginInfo[0].password;

      res.status(200).send({
        message: 'success', datas: {
          loginTimes: UserLoginInfo[0].login_times,
        }
      });
    }
  } catch (err) {
    console.error('Error: ', err);
    res.status(500).send({ message: 'Internal Server Error' });
  }
});







const server = http.createServer(app);
const io = socket(server);
//const RobotList = [];
let map_level = 1;
var Filter = require('bad-words'),
  filter = new Filter();


const players = {};
let maplimit = 15;



/*
class Robots {
  constructor(x, y, width, height, type) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;

    this.velocity = { x: 0, y: 0 };
    this.anim = null;
    this.flipped = false;
    this.type = type;

  }
}
*/




class OtherPlayers {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.velocity = { x: 0, y: 0 };
    this.anim = null;
    this.missionFinished = false;
    this.keyTaken = false;
    this.jumpTimes = 0;
    this.flipped = false;
    this.canJump = false;
    this.name = "";
    this.distanceForkey = 0;
    this.distanceForWin = 0;

  }
}


let addedPlayers = {};

var AllMessages = [];


const escape_mode = new escape_game(io, filter, players, AllMessages, maplimit, addedPlayers, listToVictory, OtherPlayers, map_level);


















function createConnection() {
  return pool;
}







async function QueryCode(query, paramsArr) {
  const connection = await pool.getConnection();
  try {
    const [results, fields] = await connection.execute(query, paramsArr);
    return results;
  } catch (err) {
    console.error('Query error: ', err);
    throw err;
  } finally {
    connection.release();
  }
}


const defaultAddUser = async (username, password, menuname) => {
  try {
    const now = new Date();
const formattedDate = now ? now.toISOString().slice(0, 19).replace('T', ' ') : null;

    const query = `INSERT INTO \`users\` (id, username, password, menuname, level, last_login_date, login_times) VALUES (?, ?, ?, ?, ?, ?, ?)`;
    const params = [null, username, password, menuname, 0, formattedDate, 0];
    const result = await QueryCode(query, params);
    console.log(result);
  } catch (err) {
    console.error('Query error: ', err);
  }
};


const controllUser = async (username, password) => {
  try {
    const loginInfo = await QueryCode(
      'SELECT username, password, menuname,login_times FROM `users` WHERE username=? AND password=?',
      [username, password]
    );
    console.log(loginInfo);
    return loginInfo;
  } catch (err) {
    console.error('Error: ', err);
    throw err;
  }
};

const controllUserName = async (username) => {
  try {
    const userInfo = await QueryCode(
      'SELECT username FROM `users` WHERE username=?',
      [username]
    );
    console.log(userInfo);
    return userInfo;
  } catch (err) {
    console.error('Error: ', err);
    throw err;
  }
};







// Klasör yükleme işlemi
const router = express.Router();


/*

router.get('/game.html', async (req, res, next) => {
  if (!(req.session.username || req.session.password)) {
    res.status(403).send('Access Denied');
  } else {
    next();
  }
});


router.get('/index.html', async (req, res, next) => {
  if (req.session.username && req.session.password) {
    res.send(directionLink('Please You must exit Before Login', '/game.html'));
  } else {
    next();
  }

})
  */

app.use('/', router);




app.use(express.static(path.join(__dirname, 'html')));
let timer = "3:00";



app.post(APILocation + '/getLevel', async (req, res, next) => {

  await res.send({
    level: escape_mode.map_level,
  });

})



// Sunucuyu belirtilen port üzerinden başlatma
server.listen(2053, () => {




  let minute = parseInt(timer.split(":")[0]);
  let second = parseInt(timer.split(":")[1]);

  let secondTime = minute * 60 + second;





  const timerInterval = setInterval(() => {

    console.log(escape_mode.map_level);
    if (escape_mode.listToVictory) {
      io.emit("take_list_info", escape_mode.listToVictory);

    }




    secondTime -= 1;


    if (secondTime <= 0) {

      escape_mode.AllMessages = [];
      secondTime = timeConvertor(timer);
      if (escape_mode.map_level < maplimit) {
        escape_mode.map_level = ((escape_mode.map_level) % (maplimit));
        escape_mode.map_level += 1;
      } else {
        escape_mode.map_level = ((escape_mode.map_level + 1) % (maplimit));
      }







    }




    io.emit("timeChange", { timer: secondTime });
  }, 1000);



  console.log('Server is running on port 2053');
});



function timeConvertor(timer) {
  let minute = parseInt(timer.split(":")[0]);
  let second = parseInt(timer.split(":")[1]);
  return minute * 60 + second;
}







// Yeni kullanıcı ekleme işlemi
function newUser(userDetail) {
  const yeniKullanici = userDetail;

  connection.query('INSERT INTO cyber_attacks_users SET ?', yeniKullanici, (error, results, fields) => {
    if (error) throw error;
    console.log('Yeni kullanıcı eklendi. Eklenen kullanıcının ID\'si:', results.insertId);
  });
}
_____


import { useState, useEffect } from 'react';
import { Container } from 'nes-ui-react';
import PhaserGame from './game/PhaserGame';
import { io } from 'socket.io-client';
import axios from 'axios';
import LoginForm from './components/LoginForm';
import SignInForm from './components/SignInForm';
import URL from './game/URL';


function App() {
  const [currentView, setCurrentView] = useState('login');
  const [alertMessage, setAlertMessage] = useState('');
  const [audioPlaying, setAudioPlaying] = useState(false);
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    const newSocket = io(URL);
    setSocket(newSocket);

    return () => newSocket.disconnect();
  }, []);

  const handleLogin = async (username, password) => {
    try {
      const response = await axios.post(`${URL}/API/login`, { username, password });
      if (response.status === 200) {
        const { loginTimes } = response.data.datas;
        localStorage.setItem('login_times', loginTimes + 1);
        setCurrentView('game');
      }
    } catch (error) {
      setAlertMessage(error.response?.status === 409 ? 'This info is not right' : 'Can\'t reach server');
    }
  };

  const handleSignIn = async (username, menuname, password) => {
    try {
      const response = await axios.post(`${URL}/API/signIn`, { username, menuname, password });
      if (response.status === 200) {
        setCurrentView('login');
      }
    } catch (error) {
      if (error.response?.status === 403) {
        setAlertMessage('This password is so weak');
      } else if (error.response?.status === 409) {
        setAlertMessage('This Info is anybody else');
      } else {
        setAlertMessage('Can\'t reach server');
      }
    }
  };

  const handleAudioPlay = () => {
    if (!audioPlaying) {
      const audio = document.getElementById('bgMusic');
      audio.play();
      setAudioPlaying(true);
    }
  };

  return (
    <Container 
      onClick={handleAudioPlay} 
      className="min-h-screen"
      style={{ backgroundColor: '#212529' }}
    >
      <audio
        id="bgMusic"
        src="./sounds/soundtracks/The Last Encounter (Original Version).mp3"
        loop
        preload="auto"
      />

      {currentView === 'login' && (
        <LoginForm 
          onSubmit={handleLogin}
          onSignInClick={() => setCurrentView('signin')}
          alertMessage={alertMessage}
        />
      )}

      {currentView === 'signin' && (
        <SignInForm
          onSubmit={handleSignIn}
          onBackClick={() => setCurrentView('login')}
          alertMessage={alertMessage}
        />
      )}

      {currentView === 'game' && <PhaserGame socket={socket} />}
    </Container>
  );
}

export default App;

_____


uyumsuzluklar varsa düzeltir misin