RESTRICT TO USA

customer  Own_1st,  Own_2nd,  Own_3rd, FirstPlayed,  Attributable Purchase, Pre_Ordered

## set key to customer, since everything will be off of that
setkeyIfNot(DT.Glitch.itunes_raw, "customer_identifier")

## Grab the unique UPCs and the unique Customer IDs.  We will CJ them into a DT 
.upcs1 <- unique(DT.Glitch.itunes_raw$upc)
.upcs2 <- unique(DT.Glitch.iradio_content$upc_fixed)
upcs <- unique(c(.upcs1, .upcs2))

.uids1 <- DT.Glitch.itunes_raw[, unique(customer_identifier)]
.uids2 <- DT.Glitch.iradio_event[, unique(customer_identifier)]
uids <- unique(c(.uids1, .uids2))

## Combine the UPCs
.uids <- unique(c(.uids1, .uids2))

## just FYI, lengths of each
          formnumb(length(.uids1))
          formnumb(length(.uids2))
          formnumb(length(intersect(.uids1, .uids2)))
          formnumb(length(uids))

          formnumb(length(.upcs1))
          formnumb(length(.upcs2))
          formnumb(length(intersect(.upcs1, .upcs2)))
          formnumb(length(upcs))
## just FYI, lengths of each

# U = user
# R = releaseid
rid.firstplay <- (-999999)
DT.Customers <- CJ(customer_identifier=(uids), releaseid=c(upcs, rid.firstplay))
DT.Customers <- DT.Customers[releaseid != 0]
setkeyIfNot(DT.Customers, kCols_UR)

## This setdiff should be zero
stopifnot(!setdiff(customers.firstplay$customer_identifier, DT.Customers$customer_identifier))

## Add in who owns what
DT.Customers[, owns := FALSE]
DT.Customers[DT.raw.using.counts, `:=`(firstTouch_perUR=i.firstTouch_perUR, preorder=i.preorder, attributable_purchase=i.attributable_purchase, owns=TRUE)]

## Add in the radio data
DT.Customers[customers.firstplay, `:=`(owns=TRUE, first_radio_listen=i.first_radio_listen_perU)]


## Mark the whole user as firstplay. Also ## First radio listen is same for all rows of a single user
DT.Customers[, firstPlay := FALSE]
DT.Customers[customers.firstplay[["customer_identifier"]], `:=`(firstPlay=TRUE, first_radio_listen=min(first_radio_listen, na.rm=TRUE))]

DT.Customers[(firstPlay), promo_was_gateway := first_radio_listen <= firstTouch_perUR]

## Add in release info
setkeyIfNot(DT.Customers, "releaseid")
setkeyIfNot(rid.info, "releaseid")

DT.Customers[rid.info, release := releasename]


