const appRoot = process.cwd();
const path = require('path');
const Sequelize = require('sequelize');
const moment = require('moment');
const uid = require('gen-uid');
const clsLogger = require('../logs/clsLogger').clsLogger;
const logger = new clsLogger();
const _ = require('lodash');
require('linqjs');

const logDB = class logDB {
  constructor() {
    this.macAddress = '00:00:00:00:00:00';
    this._dbPath = path.join(appRoot, 'logsDB.db');
    this._sequelize = new Sequelize('scheduleLog', '', '', {
      dialect: 'sqlite',
      storage: this._dbPath,
      logging: false,
      pool: {
        max: 1,
        min: 0,
        idle: 10000
      }
    });
    this.logs = this._sequelize.define('logs', {
      FileID: {type: Sequelize.INTEGER},
      FileName: {type: Sequelize.STRING(150)},
      OriginalName: {type: Sequelize.STRING(150)},
      PlayDate: {type: Sequelize.STRING(20)},
      MusicType: {type: Sequelize.INTEGER},
      // Duration: {type: Sequelize.INTEGER},
      Duration: {type: Sequelize.STRING(8)},
      uID: {type: Sequelize.STRING(40)},
      macID: {type: Sequelize.STRING(40)}
    }, {timestamp: false});
    this.initSync();
  }

   getMac() {
    let net = require('os').networkInterfaces();
    try {
      let q = _.flattenDepth(_.toArray(net)).where(c => c.family == 'IPv4' && !c.internal);
      if(q != null || q != undefined) {
        this.macAddress = q.first().mac;
      } else {
          this.macAddress = '00:00:00:00:00:00';
      }

    } catch(e) {
      logger.System(`Couldn't get mac address in logDB, err: ${e.message}`);
        this.macAddress = '00:00:00:00:00:00';
    }
  }

  async initSync() {
    this.db = await this._sequelize.sync();
    this.getMac();
    logger.System('logDB is synced');
  }

  async insertLog(msg) {
    msg.Duration = moment({hour: 0, minute: 0, second: 0}).second(msg.Duration).format("mm:ss");
    msg.uID = uid.token();
    msg.macID = this.macAddress;
    await this.logs.create(msg);
    logger.AudioEvents(`Playing log created for FileID: ${msg.FileID} - Filename: ${msg.FileName} - OriginalName: ${msg.OriginalName} - type: ${msg.MusicType}`);
  }

  async getLog(uid) {
    let id = 0;
    let date = moment().add(-15, 'd').format('YYYY-MM-DD HH:mm:ss');
    let result = await this.logs.find({where: {uID: uid}});
    if(result != null) {
      id = await result.dataValues.id;
      let q = await this.logs.findAll({where: {PlayDate: {gt: date}, id: {gt:id}}});
      let data = await q.select((c) => { return c.dataValues});
      if(data.length > 0) { return data; }
    }
  }
    async getLogFromDate(startDate,endDate,startTime,endTime,logType) {
        let now=moment().utc(true).toJSON().substr(0,11);
        //let q = await this.logs.findAll({where: {PlayDate: {gt: startDate + 'T' + startTime}, PlayDate: {lt: endDate + 'T' + endTime}}});
        let q = await this.logs.findAll();
        if(startTime.length==7)startTime='0' + startTime;
        if(endTime.length==7)endTime='0' + endTime;
        let st=new moment(startDate + 'T' + startTime).utc(true).toJSON();
        let et=new moment(endDate + 'T' + endTime).utc(true).toJSON();

        let data = q.where(c=>{return c.PlayDate>= st && c.PlayDate<=et && c.MusicType==logType})
            .select(c=>{return  {
                FileName:c.dataValues.FileName,
                OriginalName:c.dataValues.OriginalName,
                Duration:c.dataValues.Duration,
                PlayDate:c.dataValues.PlayDate,
                PlayTime:now + c.dataValues.PlayDate.substr(11,19)
               }}).orderBy(c=>c.PlayDate);
        q=null;
        let mst=moment(now + startTime).utc(true);
        let met=moment(now + endTime).utc(true);
        let q1=data.where(c=>moment(c.PlayTime).utc(true).isBetween(mst,met,null,'[]'));
        if(data.length > 0) { return q1; }else{return [];}

    }
};

const util = require('util');
const EventEmitter = require('events').EventEmitter;
util.inherits(logDB, EventEmitter);
module.exports = logDB;