import {get, isEmpty} from 'lodash';

async function searchData({db, field, keyword, folderId, perpage, offset}) {

  const searchQuery = db.knex('Entry').where('data', 'like', `%"${field}":"${keyword}"%`)
    .andWhere('folderId', folderId)
    .limit(perpage)
    .offset(offset);

  const entries = await db.raw(searchQuery, true);

  const countQuery = db.knex('Entry').count('id')
    .where('data', 'like', `%"${field}":"${keyword}"%`)
    .andWhere('folderId', folderId);

  const res = await db.raw(countQuery, true);
  const total = get(res, '[0][\'count("id")\']', 0);

  return {entries, total};
}

async function searchSourceEntry({db, keyword, folderId, perpage, offset}) {

  const searchQuery = db.knex('Entry').where('sourceEntry', 'like', `%${keyword}%`)
    .andWhere('folderId', folderId)
    .limit(perpage)
    .offset(offset);

  const entries = await db.raw(searchQuery, true);

  const countQuery = db.knex('Entry').count('id')
    .where('sourceEntry', 'like', `%${keyword}%`)
    .andWhere('folderId', folderId);

  const res = await db.raw(countQuery, true);
  const total = get(res, '[0][\'count("id")\']', 0);

  return {entries, total};
}

export default async function listFolderEntries(event, data) {

  const {page, perpage, folderId, type} = data;
  const {db, models} = this.params;
  const {Entry} = models;
  const offset = (page - 1) * perpage;
  const keyword = (data.keyword || '').trim();

  if (isEmpty(keyword)) {
    const entries = await Entry.find({folderId}, {skip: offset, limit: perpage, order: 'id'}) || [];
    const total = await Entry.count({folderId});
    this.resolve({data: entries, total});
    return;
  }

  if ('page-num' === type) {
    const {entries, total} = await searchData({db, field: 'page-num', keyword, folderId, perpage, offset});
    this.resolve({data: entries, total});
    return;
  }

  const {entries, total} = await searchSourceEntry({db, keyword, folderId, perpage, offset});
  this.resolve({data: entries, total});
}

@@ -69,17 +69,23 @@
  field, 
-k
+searchK
 eyword, 
@@ -184,33 +184,39 @@
 %60%25%22$%7Bfield%7D%22:%22$%7B
-k
+searchK
 eyword%7D%22%25%60)%0A    
@@ -434,17 +434,23 @@
 ld%7D%22:%22$%7B
-k
+searchK
 eyword%7D%22
@@ -651,33 +651,39 @@
 ourceEntry(%7Bdb, 
-k
+searchK
 eyword, folderId
@@ -769,33 +769,39 @@
 y', 'like', %60%25$%7B
-k
+searchK
 eyword%7D%25%60)%0A    .
@@ -1013,17 +1013,23 @@
 e', %60%25$%7B
-k
+searchK
 eyword%7D%25
@@ -1297,17 +1297,23 @@
 lderId, 
-t
+searchT
 ype%7D = d
@@ -1426,17 +1426,23 @@
   const 
-k
+searchK
 eyword =
@@ -1448,17 +1448,23 @@
 = (data.
-k
+searchK
 eyword %7C
@@ -1492,17 +1492,23 @@
 isEmpty(
-k
+searchK
 eyword))
@@ -1740,17 +1740,23 @@
 um' === 
-t
+searchT
 ype) %7B%0A 
@@ -1824,17 +1824,23 @@
 e-num', 
-k
+searchK
 eyword, 
@@ -1983,17 +1983,23 @@
 ry(%7Bdb, 
-k
+searchK
 eyword, 

rename keyword -> searchKeyword, type -> searchType