#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author :yzj
# @FileName :baoliu.py
# @Time :2023/5/9 11:23
# @Last Time :2023/12/5 23:45
import re
import glob
import os


class GeneProcessor:
    def __init__(self, input_file_path, output_file_path):
        self.input_file_path = input_file_path
        self.output_file_path = output_file_path

    def process_input_file(self):
        mc = []
        array = []
        retain_exp = []
        retain = []

        with open(self.input_file_path) as f:
            for line in f:
                arr = line.strip().split("\t")
                mc.append(arr)
                ch = re.search(r'\D+(\d*)[g|G]', arr[0]).group(1)
                a = [arr[i] for i in range(1, len(arr)-1)]
                array.append([ch] + a)

        for i in range(len(array)):
            chr = array[i][0]
            retain_exp.append([chr])
            retain.append([chr])
            for j in range(1, len(array[i])):
                start = i - 50
                end = i + 50
                num_gene = 0
                retain_num = 0
                exp_gene = 0
                ave_exp = 0
                length = 0
                for k in range(start, end+1):
                    if k < 0 or k >= len(array) or array[k][0] != chr:
                        continue
                    if re.search(r'\w+', mc[k][j]):
                        retain_num += 1
                    length += 1
                ave_retain = retain_num / length
                retain[i].append(ave_retain)
        return retain

    def write_output_file(self, data):
        header = "chr\tretain1\tretain2"
        with open(f"output/{self.output_file_path}", "w") as out:
            out.write(header + "\n")
            for row in data:
                out.write("\t".join(map(str, row)) + "\n")


if __name__ == '__main__':
    input_files = glob.glob("orthomcl/*")
    for line in input_files:
        file_name = os.path.basename(line).split(".")[0]
        output_file_path = f"{file_name}_retain.txt"

        gene_processor = GeneProcessor(line, output_file_path)
        processed_data = gene_processor.process_input_file()
        gene_processor.write_output_file(processed_data)
