"use strict"

const p = require("path")
const Promise = require("bluebird")
const toArr = require("../fn").toArray
const flatten = require("../fn").flatten
const write = require("../utils").write

const rgx = /[\\|\/]/g
const co = Promise.coroutine
const norm = p.normalize
const format = p.format
const sep = p.sep

module.exports = co(function * (dirs, opts) {
	dirs = flatten(toArr(dirs))
	opts = opts || {}

	const files = this._.files
	// using `watcher`? original globs passed as `prevs`
	// non-wildcard glob segments that should be trimmed!
	const globs = (this._.prevs && this._.prevs.length > 0) ? this._.prevs : this._.globs

	const trims = globs.map(g => {
		let seg = g.split(rgx)
		const idx = seg.findIndex(str => str.includes("*"))

		if (idx === -1) {
			seg.pop()
		} else {
			seg = seg.slice(0, idx)
		}

		return norm(seg.join(sep))
	}).sort((a, b) => b.length - a.length)

	return yield Promise.all(
		flatten(
			files.map(obj => {
				// store data no longer changes
				const data = obj.data

				return dirs.map(d => {
					// clone `pathObject` per target dir
					const o = { dir: obj.dir, base: obj.base }
					// replace `source` segments with `target` dir
					for (const t of trims) {
						o.dir = o.dir.replace(t, d)
					}
					// create final filepath & write to it!
					return write(format(o), data)
				})
			})
		)
	)
})

@@ -949,84 +949,8 @@
 j =%3E
- %7B%0A%09%09%09%09// store data no longer changes%0A%09%09%09%09const data = obj.data%0A%0A%09%09%09%09return
  dir
@@ -962,17 +962,16 @@
 (d =%3E %7B%0A
-%09
 %09%09%09%09// c
@@ -1007,17 +1007,16 @@
 dir%0A%09%09%09%09
-%09
 const o 
@@ -1050,17 +1050,16 @@
 .base %7D%0A
-%09
 %09%09%09%09// r
@@ -1101,17 +1101,16 @@
 et%60 dir%0A
-%09
 %09%09%09%09for 
@@ -1135,17 +1135,16 @@
  %7B%0A%09%09%09%09%09
-%09
 o.dir = 
@@ -1171,12 +1171,10 @@
 %09%09%09%09
-%09
 %7D%0A
-%09
 %09%09%09%09
@@ -1217,17 +1217,16 @@
 it!%0A%09%09%09%09
-%09
 return w
@@ -1241,16 +1241,20 @@
 mat(o), 
+obj.
 data)%0A%09%09
@@ -1258,16 +1258,10 @@
 %0A%09%09%09
-%09
 %7D)
-%0A%09%09%09%7D
 )%0A%09%09

remove unnecessary cached var inside target()