text: const uuid = require('uuid')
  const path = require('path');
  const {Device, DeviceInfo, TypeBrand} = require('../models/models')
  const ApiError = require('../error/ApiError');
  const Sequelize = require('sequelize');
  
  const Op = Sequelize.Op;
  
  class DeviceController {
      async create(req, res, next) {
          try {
              let {name, price, brandId, typeId, rating, info} = req.body
              const {img} = req.files
              let fileName = uuid.v4() + ".jpg"
              img.mv(path.resolve(__dirname, '..', 'static', fileName))
              const device = await Device.create({name, price, brandId, typeId, rating, img: fileName});
              await TypeBrand.create({typeId, brandId})
  
              if (info) {
                  info = JSON.parse(info)
                  info.forEach(i =>
                      DeviceInfo.create({
                          title: i.title,
                          description: i.description,
                          deviceId: device.id
                      })
                  )
              }
  
              return res.json(device)
          } catch (e) {
              next(ApiError.badRequest(e))
          }
  
      }
  
      async getAll(req, res) {
          let {brandId, typeId, limit, page, name} = req.query
          page = page || 1
          limit = limit || 9
          let offset = page * limit - limit
          let devices;
          if (!brandId && !typeId) {
              devices = await Device.findAndCountAll({limit, offset})
          }
          if (brandId && !typeId) {
              devices = await Device.findAndCountAll({where:{brandId}, limit, offset})
          }
          if (!brandId && typeId) {
              devices = await Device.findAndCountAll({where:{typeId}, limit, offset})
          }
          if (brandId && typeId) {
              devices = await Device.findAndCountAll({where:{typeId, brandId}, limit, offset})
          }
          if (name) {
              devices = await Device.findAndCountAll({
                  where: {
                      name: {
                          [Op.iLike]: '%' + name + '%'
                      }
                  }, limit, offset})
          }
          
          return res.json(devices)
      }
  
      async getOne(req, res) {
          const {id} = req.params
          const device = await Device.findOne(
              {
                  where: {id},
                  include: [{model: DeviceInfo, as: 'info'}]
              },
          )
          return res.json(device)
      }
  }
  
  module.exports = new DeviceController()