#! /usr/bin/env python
import glob
import os

d = {}
with open('sample-metadata.csv') as f:
    hdr = f.readline()
    samples = []
    for line in f:
        fields = line.rstrip().split(",")
        if fields[1] not in samples:
          samples.append(fields[1])
        d[fields[3]] = fields[0:3] + [fields[4]] +  [samples.index(fields[1])]
bws = glob.glob("*.bw")

track_preamble = """
track 5OH-seq_202208_bigwigs
compositeTrack on show
shortLabel 5OH-seq-2022-08-bigwigs 
longLabel 5OH-seq read coverage bigwigs
type bigWig
autoScale group
windowingFunction mean
visibility show 
maxHeightPixels 100:40:8
subGroup1 cellline Cell-line 2A7=2A7(dTAG-CLP1) 
subGroup2 drug Drug none=None 6hr=6-hours
subGroup3 strand Strand fwd=Positive rev=Negative
subGroup4 rep Replicate A=A B=B C=C 
subGroup5 dtype Type 5pcoverage=5p-end fullcoverage=Full-coverage 
subGroup6 size Size big=Large small=Small
dimensions dimX=cellline dimY=drug dimA=strand dimB=rep dimC=dtype dimD=size
sortOrder cellline=+ drug=+ strand=- rep=+
"""

print(track_preamble)

colors=[
"230,159,0",
"86,180,233",
"0,158,115",
"240,228,66",
"0,114,178",
"213,94,0"
]

for b in bws:
    bid = "_".join(b.split("_")[:3])
    vals = d[bid]
    cellline = vals[0].split(" ")[0]
    drug = vals[1]
    rep = vals[2]
    if "pos" in b:
        strand = "fwd"
    else:
        strand = "rev"
    bn = os.path.basename(b)
    dtype = bn.split("_")[4] 
    trackname = os.path.splitext(b)[0]
    color = colors[vals[4]]
    size = vals[3]
    trackname = f"50H-{cellline}-{drug}-{rep}-{strand}-{dtype}-{size}"
    
    track_template = f"track {trackname}\n"
    track_template += f"parent 5OH-seq_202208_bigwigs\n" 
    track_template += f"shortLabel {trackname}\n"
    track_template += f"bigDataUrl hydroxylseq-bw-08-2022/{b}\n"
    track_template += f"longLabel {trackname}\n"  
    track_template += f"subGroups cellline={cellline} strand={strand} drug={drug} rep={rep} dtype={dtype} size={size}\n"
    track_template += f"maxHeightPixels 100:40:8\n"
    track_template += f"color {color}\n"
    track_template += f"type bigWig\n"
    print(track_template)

