import { uniqBy } from 'lodash'
import raise from '../util/exception'
import EXCEPTION from '../config/constant/exception'
import { ProjectInfo, SubTemplateInfo } from '../controller/project'
import { db } from '../db'

const upperFirst = require('lodash.upperfirst')

export default class {
  static async getList(
    { path,
      projectId,
      offset,
      limit
    }: { path: string; projectId: string; offset: number; limit: number }) {
    const rows = db.get('project')
      .filter((item) => {
        return (path ? item.path === upperFirst(path) : true)
          && (projectId ? item.project_id === projectId : true)
      }).value() || []
    return {
      rows: rows.slice(offset, offset + limit).reverse(),
      count: rows.length
    }
  }

  static async createOne(modal: ProjectInfo) {
    const [item = {}] = db.get('project')
      .filter((item) => {
        return modal.path ? item.path === upperFirst(modal.path) :
                modal.project_id ? item.project_id === modal.project_id :
                  true
      }).value()
    if(!item.id) {
      item._create_time = Date.now()
    }
    item.id = modal.project_id
    item.env = modal.env
    item.user = modal.user
    item.name = modal.name
    item.email = modal.email
    item.choice = modal.choice
    item.version = modal.version
    item.project_id = modal.project_id
    item.template_id = modal.template_id
    const originalSubTempList = item.subTemplateList || []
    const currentSubTempList = originalSubTempList.concat(modal.subTemplateList || [])
    item.subTemplateList = uniqBy(currentSubTempList, (templateInfo: SubTemplateInfo) => templateInfo.name)
    await db.get('project')
      .updateOrAdd(modal, 'project_id')
      .write()
    return item
  }

  static async getOne(id: string) {
    const item = db.get('project')
      .find({
        id: id
      }).value()
    if (!item) {
      return raise(EXCEPTION.ITEM_NOT_EXIST)
    }
    return item
  }

  static async updateOne(id: string, { name, env, version, star }: { name: string, env: string, version: string, star: number }) {
    const item = db.get('project')
      .find({
        id: id
      }).value()
    item.name = name
    item.env = env
    item.version = version
    item.star = star
    await db.get('project')
      .updateOrAdd(item, 'project_id')
      .write()
    return item
  }

  static async deleteOne(id: string) {
    await db.get('project')
      .remove({
        id: id
      }).write()
    return {}
  }
}
