const db = require('../models');
const Utils = require('../utils');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Ui_elementsDBApi {
  static async create(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const ui_elements = await db.ui_elements.create(
      {
        id: data.id || undefined,
        element_type: data.element_type ?? null,
        name: data.name ?? null,
        settings_json: data.settings_json ?? null,
        sort_order: data.sort_order ?? 0,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    return ui_elements;
  }

  static async bulkImport(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const uiElementsData = data.map((item, index) => ({
      id: item.id || undefined,
      element_type: item.element_type ?? null,
      name: item.name ?? null,
      settings_json: item.settings_json ?? null,
      sort_order: item.sort_order ?? 0,
      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

    const ui_elements = await db.ui_elements.bulkCreate(uiElementsData, { transaction });

    return ui_elements;
  }

  static async update(id, data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const ui_elements = await db.ui_elements.findByPk(id, { transaction });

    const updatePayload = {};

    if (data.element_type !== undefined) updatePayload.element_type = data.element_type;
    if (data.name !== undefined) updatePayload.name = data.name;
    if (data.settings_json !== undefined) updatePayload.settings_json = data.settings_json;
    if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;

    updatePayload.updatedById = currentUser.id;

    await ui_elements.update(updatePayload, { transaction });

    return ui_elements;
  }

  static async deleteByIds(ids, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const ui_elements = await db.ui_elements.findAll({
      where: {
        id: {
          [Op.in]: ids,
        },
      },
      transaction,
    });

    await db.sequelize.transaction(async (innerTransaction) => {
      for (const record of ui_elements) {
        await record.update({ deletedBy: currentUser.id }, { transaction: innerTransaction });
      }
      for (const record of ui_elements) {
        await record.destroy({ transaction: innerTransaction });
      }
    });

    return ui_elements;
  }

  static async remove(id, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const ui_elements = await db.ui_elements.findByPk(id, options);

    await ui_elements.update(
      {
        deletedBy: currentUser.id,
      },
      {
        transaction,
      },
    );

    await ui_elements.destroy({
      transaction,
    });

    return ui_elements;
  }

  static async findBy(where, options) {
    const transaction = (options && options.transaction) || undefined;

    const ui_elements = await db.ui_elements.findOne({ where, transaction });

    if (!ui_elements) {
      return ui_elements;
    }

    return ui_elements.get({ plain: true });
  }

  static async findAll(filter, options) {
    filter = filter || {};
    const limit = Number(filter.limit) || 0;
    const currentPage = Number(filter.page) || 0;
    const offset = limit ? currentPage * limit : undefined;
    let where = {};

    if (filter.id) {
      where = {
        ...where,
        id: Utils.uuid(filter.id),
      };
    }

    if (filter.name) {
      where = {
        ...where,
        [Op.and]: Utils.ilike('ui_elements', 'name', filter.name),
      };
    }

    if (filter.element_type) {
      where = {
        ...where,
        element_type: filter.element_type,
      };
    }

    if (filter.sort_orderRange) {
      const [start, end] = filter.sort_orderRange;

      if (start !== undefined && start !== null && start !== '') {
        where = {
          ...where,
          sort_order: {
            ...where.sort_order,
            [Op.gte]: start,
          },
        };
      }

      if (end !== undefined && end !== null && end !== '') {
        where = {
          ...where,
          sort_order: {
            ...where.sort_order,
            [Op.lte]: end,
          },
        };
      }
    }

    let { orderBy = null } = options || {};
    if (!orderBy) {
      const sort = filter.sort || 'desc';
      const field = filter.field || 'createdAt';
      orderBy = [[field, sort]];
    }

    const { rows, count } = await db.ui_elements.findAndCountAll({
      where,
      limit: limit || undefined,
      offset,
      order: orderBy,
    });

    return {
      rows,
      count,
    };
  }

  static async findAllAutocomplete(query, limit) {
    let where = {};

    if (query) {
      where = {
        [Op.or]: [
          {
            id: {
              [Op.eq]: Utils.uuid(query),
            },
          },
          {
            name: {
              [Op.iLike]: `%${query}%`,
            },
          },
        ],
      };
    }

    const records = await db.ui_elements.findAll({
      attributes: ['id', 'name'],
      where,
      limit: Number(limit) || undefined,
      order: [['name', 'ASC']],
    });

    return records.map((record) => ({
      id: record.id,
      label: record.name,
    }));
  }
};
