#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/26 19:46
# @Author  : wjq
# @File    : dotplot_block.py
# @Software: PyCharm

import sys
import re
import os
import glob
import pandas as pd
import matplotlib.pyplot as plt

from multiprocessing import Pool


class DotplotBlock:
    def __init__(self, num_process, suffix, block_num, bed_path, block_blast_path, result_path, name_change):
        self.num_process = num_process
        self.suffix = suffix
        self.name_change = name_change
        self.block_num = block_num
        self.bed = os.path.join('.', bed_path)
        self.block_blast_path = os.path.join('.', block_blast_path)
        self.result_path = os.path.join('.', result_path)

    def select_blast(self, blast_path, block_path):
        gene_pair_list, pair_pos, last_na1, last_na2, result_pair, num = [], {}, '', '', [], 1
        gene_dit = self.get_block(block_path)
        for li in open(blast_path):
            lis = li.strip().split()
            if 'Scaffold' in li or lis[0] == lis[1]:
                continue
            if lis[0] in gene_dit and lis[1] == gene_dit[lis[0]]:
                gene_pair_list.append(f'{lis[0]}\t{lis[1]}')
            if last_na1 == lis[0] and last_na2 != lis[1]:
                num += 1
            else:
                num = 1
            pair_pos[f'{lis[0]}\t{lis[1]}'] = str(num)
            last_na1, last_na2 = lis[0], lis[1]

        for pair in gene_pair_list:
            if pair in pair_pos:
                row = pair.split('\t')
                row.append(pair_pos[pair])
                result_pair.append(row)

        blast = pd.DataFrame(result_pair)
        return blast

    def get_block(self, path):
        gene_dit = {}
        block, blocks = [], []
        for li in open(path):
            li = li.strip()
            if '>' in li:
                if len(block) >= self.block_num:
                    for row in block:
                        rows = re.split('\\s', row)
                        gene_dit[rows[0]] = rows[2]
                    # blocks.append(block)
                block = []
            elif any(([x in li for x in ['overlap', 'LOCALE',
                                         'self', 'the', '>']])):
                continue
            elif li:
                block.append(li)

        return gene_dit

    def plot_chr1(self, lens, gl, gl2, step, mark, name):  # 竖物种
        gl_start, n, start_x = 11/12, 0, 1/12
        mark_y = 17/240
        align = dict(family='Times New Roman', style='normal', horizontalalignment="center", verticalalignment="center")###染色体号
        align1 = dict(family='Times New Roman', style='italic', horizontalalignment="center", verticalalignment="center")###物种拉丁文
        for k in lens.index:
            n += float(lens.at[k, 1])
            mark_new = str(mark) + str(k)
            x = gl_start - float(n) * step
            mark_x = x + 0.5 * float(lens.at[k, 1]) * step
            plt.plot([start_x, start_x + gl2], [x, x], linestyle='-', color='black', linewidth=0.125)
            plt.plot([start_x, start_x + gl2], [x, x], linestyle='-', color='black', linewidth=0.375, alpha=0.5)
            plt.text(mark_y, mark_x, mark_new, color='black', fontsize=15, rotation=0, weight='semibold', **align)
        plt.plot([start_x, start_x + gl2], [gl_start, gl_start], linestyle='-', color='black', linewidth=0.375,
                 alpha=0.5)
        plt.plot([start_x, start_x + gl2], [gl_start, gl_start], linestyle='-', color='black', linewidth=0.125)
        plt.text(mark_y-0.04, 0.5 * (2 * gl_start - gl), name, color='black', fontsize=20, rotation=90,
                 weight='semibold', **align1)

    def plot_chr2(self, lens, gl, gl2, step, mark, name):
        gl_start, n, start_x = 1/12, 0, 11/12
        mark_y = 223/240
        align = dict(family='Times New Roman', style='normal', horizontalalignment="center", verticalalignment="center")
        align1 = dict(family='Times New Roman', style='italic', horizontalalignment="center", verticalalignment="center")
        for k in lens.index:
            n += float(lens.at[k, 1])
            mark_new = str(mark) + str(k)
            x = gl_start + float(n) * step
            mark_x = x - 0.5 * float(lens.at[k, 1]) * step
            plt.plot([x, x], [start_x, start_x - gl2], linestyle='-', color='black', linewidth=0.125)
            plt.plot([x, x], [start_x, start_x - gl2], linestyle='-', color='black', linewidth=0.375, alpha=0.5)
            plt.text(mark_x, mark_y, mark_new, color='black', fontsize=15, rotation=0, weight='semibold', **align)
        plt.plot([gl_start, gl_start], [start_x, start_x - gl2], linestyle='-', color='black', linewidth=0.375,
                 alpha=0.5)
        plt.plot([gl_start, gl_start], [start_x, start_x - gl2], linestyle='-', color='black', linewidth=0.125)
        plt.text(0.5 * (2 * gl_start + gl)+0.07, mark_y + 0.03, name, color='black', fontsize=20, rotation=0,
                 weight='semibold', **align1)

    def gene_location(self, gff, lens, step):
        loc_gene, dict_chr, n = {}, {}, 0
        for i in lens.index:
            dict_chr[str(i)] = n
            n += float(lens.at[i, 1])
        for k in gff.index:
            if gff.loc[k, 0] not in dict_chr:
                continue
            loc = (float(dict_chr[gff.loc[k, 0]]) + float(gff.loc[k, 6])) * step
            loc_gene[gff.loc[k, 5]] = loc
        return loc_gene

    def pair_positon(self, data, loc1, loc2, colors):
        pos1, pos2, newcolor = [], [], []
        gl_start1, gl_start2 = 11 / 12, 1 / 12
        for index, k in data.iterrows():
            x = gl_start1 - loc1[k[0]]
            y = gl_start2 + loc2[k[1]]
            pos1.append(y)
            pos2.append(x)
            if k[2] == '1':
                color = colors[0]
            else:
                color = colors[1]

            newcolor.append(color)
        return pos1, pos2, newcolor

    def plotfig(self, spec1, spec2):
        plt.figure(figsize=(8, 8), dpi=300)
        root = plt.axes([0, 0, 1, 1])
        gff_1 = pd.read_csv(f'{self.bed}/{spec1}.new.gff', sep="\t", header=None)
        gff_2 = pd.read_csv(f'{self.bed}/{spec2}.new.gff', sep="\t", header=None)
        gff_1[0] = gff_1[0].astype('str')
        gff_2[0] = gff_2[0].astype('str')
        lens_1 = pd.read_csv(f'{self.bed}/{spec1}.lens', sep="\t", header=None, index_col=0)
        lens_2 = pd.read_csv(f'{self.bed}/{spec2}.lens', sep="\t", header=None, index_col=0)
        gl1, gl2 = 5/6, 5/6
        step1 = gl1 / float(lens_1[1].sum())
        step2 = gl2 / float(lens_2[1].sum())
        self.plot_chr1(lens_1, gl1, gl2, step1, '', self.name_change[spec1])
        self.plot_chr2(lens_2, gl1, gl2, step2, '', self.name_change[spec2])
        gene_loc_1 = self.gene_location(gff_1, lens_1, step1)
        gene_loc_2 = self.gene_location(gff_2, lens_2, step2)
        blast = self.select_blast(f'{self.block_blast_path}/{spec1}_{spec2}.{self.suffix}',
                                  f'{self.block_blast_path}/{spec1}_{spec2}.block.rr.txt')
        blast = blast[(blast[0].isin(gene_loc_1.keys())) & (blast[1].isin(gene_loc_2.keys()))]
        colors = ['orangered', 'gray']
        x, y, colors = self.pair_positon(blast, gene_loc_1, gene_loc_2, colors)
        plt.scatter(x, y, s=1, c=colors, alpha=0.5, edgecolors=None, linewidths=0)
        root.set_xlim(0, 1)
        root.set_ylim(0, 1)
        root.set_axis_off()
        plt.savefig(f'{self.result_path}/{spec1}_{spec2}.{self.block_num}.2400.png')
        # plt.savefig(f'{self.result_path}/{spec1}_{spec2}.{self.block_num}.2400.pdf')

    def main(self):
        p = Pool(self.num_process)
        blasts = glob.glob(f'{self.block_blast_path}/*.blast')
        for file in blasts:
            fna = os.path.basename(file)
            spec1, spec2 = fna.split('.')[0].split('_')
            p.apply_async(self.plotfig, args=(spec1, spec2))

        p.close()
        p.join()


if __name__ == '__main__':
    num_process = 1
    blast_suffix = 'blast'
    block_num = int(sys.argv[3])
    bed_path = ''
    block_blast_path = ''
    result_path = ''
    name_change = {f"{sys.argv[1]}": f"{sys.argv[1]}", f"{sys.argv[2]}": f"{sys.argv[2]}"}  # 简写对应的名称
    p = DotplotBlock(num_process, blast_suffix, block_num, bed_path, block_blast_path, result_path, name_change)
    p.main()


