require('dotenv').config()
const path          = require('path')
const nameThisColor = require('name-this-color')
const fs            = require('fs')
const lineReader    = require('line-reader')

const colorsScss = path.join(__dirname, `../../../../public/app/themes/${process.env.WP_THEME}/resources/assets/styles/atoms/colors.scss`)
let colors = []

lineReader.eachLine(colorsScss, (line, last) => {
	let color = line.replace('--', '').split(':')
	color = color[1].trim().replace(';', '')
	colors.push(color)

	if (last) {
		getColors(colors)
		return false
	}
})

function getColors (colors) {
	const stream = fs.createWriteStream(colorsScss)
	let krikVariables = []

	colors = nameThisColor(colors)
	colors.map(element => { element.sass = `$${element.name}: ${element.hex};` })
	colors.forEach((value, index, array) => {
		array[index] = value.sass
		krikVariables.push(`$c-${index + 1}: $${value.name};`)
	})

	stream.once('open', (fd) => {
		colors.forEach(value => {
			stream.write(`${value}\n`)
		})
		stream.write('\n')
		krikVariables.forEach(value => {
			stream.write(`${value}\n`)
		})
		stream.end()
	})
}
