#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
    USAGE :
    python3 sample_list_builder.py --samples ../../sample --forw _R1 --rev _R2 --ext .fastq.gz -o ../../data/samples.yml
    edited 11/2020 :
    SHOULD NOT BE USED, see issue#5
"""

import os
import sys
import argparse
import re
from yaml import load, dump
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

def run_samples(sample_dir,out):

    if not os.path.isdir(sample_dir):
        raise NameError(f"{sample_dir} doesn't exist")
        exit(1)
    cpt = 0
    sample_dict = {}
    for file in sorted(os.listdir(sample_dir)):
        if re.search("fq|fastq", file,re.IGNORECASE):
            cpt += 1
            # sample_name = re.split("(?i)(_r.|.r.)",file)[0]
            sample_name = file.split("_")[0]
            reads = re.search("(?i)(_r.|.r.)", file,re.IGNORECASE)[0]
            ext = re.search("(?i)(.fastq|.fq)", file,re.IGNORECASE)[0]
            if sample_name not in sample_dict.keys():
                sample_dict[sample_name]=[os.path.join(os.path.abspath(sample_dir), file)]
            else:
                sample_dict.get(sample_name).insert(1, os.path.join(os.path.abspath(sample_dir), file))
    # k = sample_dict.keys()
    # to_remove = []
    # for i in k:
    #     if len(sample_dict.get(i)) != 2:
    #         print(i, " droped from yaml file because missing file\n")
    #         print(i, " - file present : " ,sample_dict.get(i), "\n")
    #         to_remove.append(i)

    # for i in to_remove:
    #     sample_dict.pop(i)

    stream = open(os.path.join(out, "samples.yaml"), 'w')
    dump(sample_dict, stream, indent=3)
    stream.close()
