/*******************************************************************************
 * Licensed Materials - Property of IBM
 * (c) Copyright IBM Corporation 2019. All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * Use, duplication or disclosure restricted by GSA ADP Schedule
 * Contract with IBM Corp.
 *******************************************************************************/
/* Copyright (c) 2020 Red Hat, Inc. */
'use strict'

import React from 'react'
import jsYaml from 'js-yaml'
import YamlParser from '../../lib/client/yaml-helper'
import msgs from '../../nls/platform.properties'
import _ from 'lodash'

// itemKeys: members of item that get their own chart section
export const dumpAndParse = (item, itemKeys=[]) => {

  const tempItem = _.cloneDeep(item)

  const removeStatus = (obj) => {
    if (obj.raw) {
      delete obj.raw['status']
    }
  }
  removeStatus(tempItem)
  // use this to sort the keys generated by safeDump
  const sortKeys = (a,b) => {
    if (a==='name' && b!=='name') {
      return -1
    } else if (a!=='name' && b==='name') {
      return 1
    } else if (a==='namespace' && b!=='namespace') {
      return -1
    } else if (a!=='namespace' && b==='namespace') {
      return 1
    }
    return a.localeCompare(b)
  }

  // dump parsed data into yaml sections
  let yaml, row=0
  let parsed
  const yamls = []
  if (tempItem.raw) {
    yaml = jsYaml.safeDump(tempItem.raw, {sortKeys})
    // create objects from the dumped yaml to create with row #'s
    parsed = new YamlParser().parse(yaml)
    row += yaml.split('\n').length
    yamls.push(yaml)
  }

  // then dump the arrays within parsed
  itemKeys.forEach(key=>{
    const arr = tempItem[key]
    if (Array.isArray(arr)) {
      parsed[key] = []
      arr.forEach(member=>{
        if (member.raw) {
          yaml = jsYaml.safeDump(member.raw, {sortKeys})
          // create objects from the dumped yaml to create with row #'s
          const synced = new YamlParser().parse(yaml, row)
          synced.$r = row
          parsed[key].push(synced)
          row += yaml.split('\n').length
          yamls.push(yaml)
        }
      })
    }
  })
  return {yaml: yamls.join('---\n'), parsed}
}

export const saveLoad = (data) => {
  return jsYaml.safeLoadAll(data)
}

export const getResourceType = (item, locale, key) => {
  return key ? _.get(item, key) : item.resourceType
}

export const getClusterLink = (item) => {
  const { cluster: { consoleURL = '', metadata} } = item

  return consoleURL !== '' ?
    <a target='_blank' rel='noopener noreferrer' href={`${consoleURL}/console`}>{metadata.name}</a>
    : metadata.name
}

export function transformPVStatus(item, locale) {
  const translatedStatus = msgs.get(`table.cell.status.${item.status.toLowerCase()}`, locale)
  return translatedStatus ===  `table.cell.status.${item.status.toLowerCase()}`
    ? translatedStatus
    : item.status
}

export const parse = (yaml, validator, locale) => {
  let absLine=0
  const parsed = {}
  const yamls = yaml.split(/^---$/gm)
  const exceptions = []
  // check for syntax errors
  try {
    yamls.forEach((snip)=>{
      const obj = jsYaml.safeLoad(snip)
      const key = _.get(obj, 'kind', 'unknown')
      let values = parsed[key]
      if (!values) {
        values = parsed[key] = []
      }
      const post = snip.endsWith('\n')
      snip = snip.trim()
      const $synced = new YamlParser().parse(snip, absLine)
      $synced.$r = absLine
      $synced.$l = snip.split('\n').length
      values.push({$raw: obj, $yml: snip, $synced})
      absLine += $synced.$l
      if (post) {
        absLine++
      }
    })
  } catch (e) {
    const {mark={}, reason, message} = e
    const {line=0, column=0} = mark
    exceptions.push({
      row: line+absLine,
      column,
      text: _.capitalize(reason||message),
      type: 'error',
    })
  }

  // validate
  if (validator && exceptions.length===0) {
    validator(parsed, exceptions, locale)
  }

  return {parsed, exceptions}
}
