export function createQueryString(params: { [code: string]: number|string|string[] }) {
  const result = Object.entries(params).reduce((result, [key, value]) => {
    if (Array.isArray(value)) {
      result += value.map((v) => `${key}=${encodeURIComponent(String(v))}&`).join('')
    } else {
      result += `${key}=${encodeURIComponent(String(value))}&`
    }

    return result
  }, '?')

  if (Object.keys(params).length > 0) return result.slice(0, result.length - 1)

  return result
}

export function createQueryCommaString(params: { [code: string]: number|string|string[] }) {
  const result = Object.entries(params).reduce((result, [key, value]) => {
    if (Array.isArray(value)) {
      result += value.map((v, index) => (index === 0 ? `${key}=${encodeURIComponent(String(v))},` : `${encodeURIComponent(String(v))},`)).join('').replace(/,$/, '&')
    } else {
      result += `${key}=${encodeURIComponent(String(value))}&`
    }

    return result
  }, '?')

  if (Object.keys(params).length > 0) return result.slice(0, result.length - 1)

  return result
}

export function checkEndpointOptionAndCreateQueryString(endpoint: string, queryParams: { [code: string]: number|string|string[] }) {
  let resultUrl: string = ''
  if (endpoint.includes('?') && queryParams) {
    const changedSymbols = Object.values(createQueryString(queryParams)).map((item: string) => {
      if (item.includes('?')) return '&'
      return item
    }).join('')

    resultUrl = endpoint + changedSymbols
  } else {
    resultUrl = endpoint + createQueryString(queryParams)
  }

  return resultUrl
}

export const modalIds: string[] = []

export function isLastModalID(modalId: string): boolean {
  return modalIds[modalIds.length - 1] === modalId
}
