import { FutureInfo, Margin, MarketInfo, ProfitAndLoss, UserRole } from './typings'
import { keccak256, toUtf8Bytes } from 'ethers'

export const profitAndLossTotal = (input: ProfitAndLoss) => {
  return input.accruedLPFee + input.netFutureValue - input.incurredFee
}

export const marginTotal = (input: Margin) => {
  return input.collateral + profitAndLossTotal(input.profitAndLoss)
}

export const getUserRoleBytes = (role: UserRole) => {
  return keccak256(toUtf8Bytes(role));
}

const monthsAlias: Record<number, string> = {
  1: 'JAN',
  2: 'FEB',
  3: 'MAR',
  4: 'APR',
  5: 'MAY',
  6: 'JUN',
  7: 'JUL',
  8: 'AUG',
  9: 'SEP',
  10: 'OCT',
  11: 'NOV',
  12: 'DEC'
}

const getShortDate = (timestamp: number) => {
  const date = new Date(timestamp)
  const month = monthsAlias[(date.getMonth() + 1)]
  const year = (date.getFullYear() - 2000)
  return `${month}${year}`
}

const trimString = (value: string) => {
  return value.trim().toLowerCase().replaceAll(' ', '-').toUpperCase()
}

export const getFutureAlias = (market: MarketInfo, future: FutureInfo) => {
  const { termStart, termLength } = future

  const sourceName = trimString(market.descriptor.sourceName)
  const [instrumentName] = trimString(market.descriptor.instrumentName).split('-')
  const termEnd = +(termStart + termLength).toString() * 1000
  const formattedDate = getShortDate(termEnd)
  if(sourceName === 'COINDESK-INDICES') {
    return `${instrumentName}-${formattedDate}`
  }
  return `${sourceName}-${instrumentName}-${formattedDate}`
}
