const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;

const tools = require('../tools/general');

mongoose.Promise = global.Promise;
mongoose.level = "F";


// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
  schema.options.usePushEach = true
});

const { ObjectId } = require('mongodb');

const HoursSchema = new Schema({
  idapp: {
    type: String,
  },
  userId: {
    type: String
  },
  descr: {
    type: String,
  },
  todoId: {
    type: String,
  },
  date: {
    type: Date,
    default: Date.now
  },
  time_start: {
    type: Number,
  },
  time_end: {
    type: Number,
  },
  hours: {
    type: Number,
  },
});

var Hours = module.exports = mongoose.model('Hours', HoursSchema);

module.exports.getFieldsForSearch = function () {
  return [{ field: 'descr', type: tools.FieldType.string }]
};

module.exports.executeQueryTable = function (idapp, params) {
  params.fieldsearch = this.getFieldsForSearch();
  return tools.executeQueryTable(this, idapp, params);
};

module.exports.findAllIdApp = async function (idapp) {
  const myfind = { idapp };

  return await Hours.find(myfind);
};

module.exports.correggiHours = async function (idapp) {
  const myfind = { idapp };

  const myarr = await Hours.find(myfind);

  for (const rec of myarr) {

    rec.userId = rec.userId.toString();
    let ris = await Hours.findOneAndUpdate({ _id: rec._id }, { $set: { userId: rec.userId } }, { new: false } );
    if (!!ris) {
      console.log('ris', ris);
    }
  }

};

module.exports.getHoursByIdCat = async function (idapp, userId, idCat, date_start, date_end) {
  const myfind = [
    {
      $match: {
        idapp,
        userId,
        date: { $gte: new Date(date_start), $lte: new Date(date_end) },
        todoId: idCat
      }
    },
    {
      $group:
        {
          _id: "$todoId",

          totalAmount: {
            $sum: "$hours"
          },
          count: {
            $sum: 1
          }
        }
    }
  ];

  try {
    const ris = await Hours.aggregate(myfind);
    if (ris.length > 0) {
      return ris[0].totalAmount;
    } else {
      return 0;
    }
  } catch (e) {
    console.log('e', e);
    return 0;
  }
};

module.exports.getTotalHoursByDate = async function (idapp, userId, date) {
  const dateini = date;
  const datefin = tools.AddDate(date, 1);


  const myfind = [
      {
        $match: {
          idapp,
          userId,
          hours: { $gt: 0 },
          date:
            {
              $gte: dateini,
              $lt: datefin,
            }
        },
      },
      {
        $group:
          {
            _id: { $dateToString: { format: "%Y-%m-%d", date: "$date", timezone: 'Europe/Rome'   } },

            totalAmount: {
              $sum: "$hours"
            },
            count: {
              $sum: 1
            }
          }
      }
    ]
  ;



  try {
    const ris = await Hours.aggregate(myfind);
    if (ris.length > 0) {
      // console.log('[',dateini, '-', datefin, '] TOT', ris[0].totalAmount)
      return ris[0].totalAmount;
    } else {
      return 0;
    }
  } catch (e) {
    console.log('e', e);
    return 0;
  }
}
;

module.exports.getHoursByDate = async function (idapp, userId, date) {

  // console.log(mystr);
  const myfind =
    {
      idapp,
      userId,
      hours: { $gt: 0 },
      date: {
        $gte: date,
        $lt: tools.AddDate(date, 1)
      }
    };

  try {
    return await Hours.find(myfind);
  } catch (e) {
    console.log('e', e);
    return 0;
  }
};

module.exports.calculateHoursTodo = async function (idtodo) {
  const Hours = this;

  if (idtodo) {
    const myfind = [
      {
        $match: { todoId: idtodo }
      },
      {
        $group:
          {
            _id: "$todoId",

            totalAmount: {
              $sum: "$hours"
            },
            count: {
              $sum: 1
            }
          }
      }
    ];

    try {
      const ris = await Hours.aggregate(myfind);
      if (ris.length > 0) {
        return ris[0].totalAmount;
      } else {
        return 0;
      }
    } catch (e) {
      console.log('e', e);
      return 0;
    }
  } else {
    return 0;
  }

};

module.exports.createIndexes()
  .then(() => { })
  .catch((err) => { throw err; });

