# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-11-01 19:25
from __future__ import unicode_literals

import hashlib
from django.db import migrations
from django.db.models import Max


SC_WGS_BAM_NAME_TEMPLATE = "-".join([
    "{dataset_type}",
    "{sample_id}",
    "{library_type}",
    "{library_id}",
    "lanes_{lanes_hash}",
    "{aligner}",
    "{reference_genome}",
])

SC_WGS_FQ_NAME_TEMPLATE = "-".join([
    "{dataset_type}",
    "{sample_id}",
    "{library_type}",
    "{library_id}",
    "{lane}",
])

def get_lane_str(lane):
    if lane["lane_number"] == "":
        return "{}".format(lane["flowcell_id"])

    # Include lane number
    return "{}_{}".format(lane["flowcell_id"], lane["lane_number"])


def get_lanes_hash(lanes):
    if not lanes:
        raise ValueError("bam with no lanes")

    # More than two lanes
    lanes = ", ".join(sorted([get_lane_str(a) for a in lanes]))
    lanes = hashlib.md5(lanes)
    return "{}".format(lanes.hexdigest()[:8])


def get_created_time(dataset):
    return dataset.file_resources.all().aggregate(Max('created'))['created__max']


def rename_datasets(apps, schema_editor):
    SequenceDataset = apps.get_model('tantalus', 'SequenceDataset')
    datasets = dict()
    for dataset in list(SequenceDataset.objects.filter(library__library_type='SC_WGS').all()):
        lane_infos = []
        for lane in dataset.sequence_lanes.all():
            lane_infos.append({'flowcell_id': lane.flowcell_id, 'lane_number': lane.lane_number})
        if dataset.dataset_type == 'BAM':
            new_name = SC_WGS_BAM_NAME_TEMPLATE.format(
                dataset_type=dataset.dataset_type,
                sample_id=dataset.sample.sample_id,
                library_type=dataset.library.library_type,
                library_id=dataset.library.library_id,
                lanes_hash=get_lanes_hash(lane_infos),
                aligner=dataset.aligner,
                reference_genome=dataset.reference_genome,
            )
        elif dataset.dataset_type == 'FQ':
            new_name = SC_WGS_FQ_NAME_TEMPLATE.format(
                dataset_type=dataset.dataset_type,
                sample_id=dataset.sample.sample_id,
                library_type=dataset.library.library_type,
                library_id=dataset.library.library_id,
                lane=get_lane_str(lane_infos[0]),
            )
        if new_name in datasets:
            if get_created_time(dataset) > get_created_time(datasets[new_name]):
                print('a, deleting {} over {}'.format(
                    datasets[new_name].file_resources.all()[0].filename,
                    dataset.file_resources.all()[0].filename))
                datasets[new_name].file_resources.all().delete()
                datasets[new_name].delete()
                datasets[new_name] = dataset
            else:
                print('b, deleting {} over {}'.format(
                    dataset.file_resources.all()[0].filename,
                    datasets[new_name].file_resources.all()[0].filename))
                dataset.file_resources.all().delete()
                dataset.delete()
                dataset = datasets[new_name]
        else:
            datasets[new_name] = dataset
        dataset.name = new_name
        dataset.save()


class Migration(migrations.Migration):

    dependencies = [
        ('tantalus', '0072_auto_20181101_1857'),
    ]

    operations = [
        migrations.RunPython(rename_datasets),
    ]
