import * as React from "react"
import styled from "styled-components"

import { RibbonBadgeWithIcon } from "../Badge"
import gql from "graphql-tag"
import { BadgeIconNameEnum } from "../Badge/components/BadgeIcon"

const abbreviate = require("number-abbreviate")

type BadgeInfo = {
  name: BadgeIconNameEnum
  label: string
}
export function getBookBadgeInfoFromBookData(book: BookItemData) {
  const badges: BadgeInfo[] = []
  if (book.totalIncome) {
    if (book.totalIncome.gold > 50000) {
      badges.push({
        label: abbreviate(book.totalIncome.gold, 1) + "",
        name: "jelly"
      })
    }
  }

  badges.push({
    label: abbreviate(book.viewCount || 0, 1) + "",
    name: "view"
  })

  badges.push({
    label: abbreviate(book.countAllAdore || 0, 0) + "",
    name: "miniheart"
  })

  if (book.ratingSummary) {
    const avg = book.ratingSummary.average || 0
    badges.push({
      label: abbreviate(avg.toFixed(2), 0) + "",
      name: "rating"
    })
  }

  return badges
}

const BookRibbonStyleContainer = styled.div.attrs({
  className: "BookRibbonBadges"
})`

`
type BookRibbonBadgeComponent = React.SFC<{ book: BookItemData }> & {
  fragments: { book: any }
}
export const BookRibbonBadges: BookRibbonBadgeComponent = Object.assign(
  (props) => {
    return (
      <BookRibbonStyleContainer>
        {getBookBadgeInfoFromBookData(props.book).map((badge) => {
          return <RibbonBadgeWithIcon key={badge.name} {...badge} />
        })}
      </BookRibbonStyleContainer>
    )
  },
  {
    fragments: {
      book: gql`
        fragment Book__BookRibbonBadge__BookData on Book {
          _id
          viewCount
          ratingSummary {
            average
          }
          countAllAdore
          commentCount
          contentRating
          episodeCount
          totalIncome {
            silver
            gold
          }
        }
      `
    }
  }
)
