const WebSocket = require('ws');
const { generateAmplitudeCycle } = require('./generator');
const { ThresholdManager } = require('./threshold');
const Parse = require('parse/node');

// Parse初始化
Parse.initialize('dev', 'devmk'); // appId, masterKey
Parse.serverURL = 'http://dev.fmode.cn:1337/parse';

const wss = new WebSocket.Server({ port: 8080 });
console.log('WebSocket server started on ws://localhost:8080');

// 阈值管理器实例
const thresholdManager = new ThresholdManager();

function getStageByIndex(index, stageDurations) {
  let sum = 0;
  for (let i = 0; i < stageDurations.length; i++) {
    sum += stageDurations[i];
    if (index < sum) return i;
  }
  return stageDurations.length - 1;
}

wss.on('connection', (ws, req) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const device = url.searchParams.get('device') || 'A';

  console.log('Client connected, device:', device);
  ws.send(JSON.stringify({ type: 'info', msg: 'Connected to amplitude server.', device }));

  let { cycle, stages, duration } = generateAmplitudeCycle();
  let index = 0;

  const timer = setInterval(() => {
    if (index >= cycle.length) {
      thresholdManager.addNormalCycle(cycle, stages);
      ({ cycle, stages, duration } = generateAmplitudeCycle());
      index = 0;
    }
    const value = cycle[index];
    const { isAbnormal, lower, upper } = thresholdManager.checkAbnormal(value, index, stages);
    const stage = getStageByIndex(index, stages);
    const data = {
      value,
      index,
      isAbnormal,
      lower,
      upper,
      stage,
      timestamp: Date.now()
    };
    console.log('index:', index, 'stage:', stage, 'lower:', lower, 'upper:', upper);
    ws.send(JSON.stringify(data));
    // 写入 Parse Server
    const AmplitudeData = Parse.Object.extend('AmplitudeData');
    const amplitudeData = new AmplitudeData();
    amplitudeData.set('value', value);
    amplitudeData.set('index', index);
    amplitudeData.set('isAbnormal', isAbnormal);
    amplitudeData.set('lower', lower);
    amplitudeData.set('upper', upper);
    amplitudeData.set('stage', stage);
    amplitudeData.set('timestamp', new Date());
    amplitudeData.save().catch(err => {
      console.error('Parse save error:', err.message);
    });
    index++;
  }, 1000);

  ws.on('close', () => {
    clearInterval(timer);
    console.log('Client disconnected');
  });
}); 