import {get, post, put, remove} from './apiHelpers.js'
import {convertList, convertObject} from '@helpers/adapter/adapter.js'
import {devUsersList} from './StaticData.js'

/**
 * Интерфейс пользователя
 * @typedef {Object} User
 * @param {Number}  id
 */

const adapter_config = {
  id: "id",
  first_name: "firstName",
  last_name: "lastName",
  email: "email",
  role: "role",
}

class Users {
  /**
   * Класс управления роутерами
   * @param {String} apiAddr - path to service
   * @param {Object | undefined} params - Конфиг настроек
   * @param {'prod' | 'test'} params.mode - Конфиг настроек
   */
  constructor(apiAddr, params = {mode: 'prod'}) {
    this.apiAddr = apiAddr
    this.config  = adapter_config
    this.mode    = params.mode
  }

  /**
   *
   * @param {Object} params - Конфиг настроек
   * @param {'prod' | 'dev'} params.mode - Конфиг настроек
   * @returns {Promise<*[]> | *[]}
   */
  async getUsers(params = {mode: 'prod'}) {
    if (params.mode === "dev") {
      return devUsersList
    }
    let res = await get(`${this.apiAddr}/users`)
    let updatedUsers = convertList(res.data, {config: this.config})
    return updatedUsers
  }

  /**
   *
   * @param {Number} id - Сервис id, если id не указан, отображается список всех роутеров
   * @param {'dev' | 'prod'} mode - Сервис id, если id не указан, отображается список всех роутеров
   * @returns {Promise<Array<User>> | any}
   */
  async getUsersByServiceId(id, mode) {
    if (mode === "dev") {
      return devUsersList
    }
    let res = await get(`${this.apiAddr}/users/by_server/${id}`)
    let updatedUsers = convertList(res.data, {config: this.config})
    return updatedUsers
  }

  /**
   *
   * @param {User} userData
   * @returns {Promise<Object>}
   */
  async createUser(userData) {
    const newUser = await post(`${this.apiAddr}/users`, userData)
    return convertObject(newUser, {config: this.config})
  }

  /**
   *
   * @param {User} userData
   * @returns {Promise<Object>}
   */
  async updateUser(userData) {
    const updatedUserData = {...userData}
    delete updatedUserData.id
    const newUser = await put(`${this.apiAddr}/users/${userData.id}`, updatedUserData)
    return convertObject(newUser, {config: this.config})
  }

  /**
   *
   * @param {Number} userId - Сервис id, если id не указан, отображается список всех роутеров
   * @returns {Promise<Object>}
   */
  async removeUser(userId) {
    const removedUser = await remove(`${this.apiAddr}/users/${userId}`)
    return convertObject(removedUser, {config: this.config})
  }


  /**
   * Функция запускает список запросов к апишке и логает ответы
   * @returns {Promise<String>}
   */
  async test() {
    console.log("_______START TEST_______")

    const allUsers = await this.getUsers()
    console.log("allUsers", allUsers)
    const serverUser = await this.getUserById(1)
    console.log("getUserById 1", serverUser)
    const newUser = await this.createUser({
      "server_id": 1,
      "path": "/",
      "role": 1,
      "description": "tests swagger",
      "deepness": 6,
      "order": 0,
      "is_cb_on": true,
      "cb_request_limit": 100,
      "cb_min_requests": 100,
      "cb_error_threshold_percentage": 0.35,
      "cb_interval_duration": 2000000,
      "cb_open_state_timeout": 1000000
    })
    console.log("newUser", newUser)
    const updatedUser = await this.updateUser({
      "path": "/updated_path/",
      "description": "updated_description",
      "id": newUser.id
    })
    console.log("updatedUser", updatedUser)
    const removedUser = await this.removeUser(newUser.id)
    console.log("removedUser", removedUser)

    const newUser1 = await this.createUser({
      "server_id": 1,
      "path": "/",
      "role": 1,
      "description": "tests swagger",
      "deepness": 6,
      "order": 0,
      "is_cb_on": true,
      "cb_request_limit": 100,
      "cb_min_requests": 100,
      "cb_error_threshold_percentage": 0.35,
      "cb_interval_duration": 2000000,
      "cb_open_state_timeout": 1000000
    })
    const newUser2 = await this.createUser({
      "server_id": 1,
      "path": "/",
      "role": 1,
      "description": "tests swagger",
      "deepness": 6,
      "order": 0,
      "is_cb_on": true,
      "cb_request_limit": 100,
      "cb_min_requests": 100,
      "cb_error_threshold_percentage": 0.35,
      "cb_interval_duration": 2000000,
      "cb_open_state_timeout": 1000000
    })
    const newUser3 = await this.createUser({
      "server_id": 1,
      "path": "/",
      "role": 1,
      "description": "tests swagger",
      "deepness": 6,
      "order": 0,
      "is_cb_on": true,
      "cb_request_limit": 100,
      "cb_min_requests": 100,
      "cb_error_threshold_percentage": 0.35,
      "cb_interval_duration": 2000000,
      "cb_open_state_timeout": 1000000
    })

    const actions = [
      {
        ...newUser1,
        action: "update",
        "path": "/updated_path2/",
        "description": "updated_description2",
      }, {
        ...newUser2,
        action: "update",
        "path": "/updated_path3/",
        "description": "updated_description3",
      }, {
        ...newUser3,
        action: "remove"
      },
      {
        action: "create",
        "server_id": 1,
        "path": "/lalalala/lalalal",
        "role": 1,
        "description": "new_route_created",
        "deepness": 6,
        "order": 0,
        "is_cb_on": true,
        "cb_request_limit": 100,
        "cb_min_requests": 100,
        "cb_error_threshold_percentage": 0.35,
        "cb_interval_duration": 2000000,
        "cb_open_state_timeout": 1000000
      }
    ]

    const mutationsList = await this.updateGroupUsers(actions)
    console.log("mutationsList", mutationsList)
    console.log("________END TEST________")

    return "ok"
  }
}

export default Users