"""FORked report PlumIs"""

import os
import sys
import shutil

from recon import Recon
# from folda import Folda

class Forpi:

    def __init__(self, plumi, do_verbose=False):
        self.plumi = plumi
        self.e = plumi.e
        # # if there is no plumi folder, the forpi folder
        # # is created provided that there is a parent
        # # report. If there is a plumi folder, the
        # # forpi needs to be checked for contents
        # # if the check finds that there is no need
        # # for any file any more it removes the folder
        self.mother_repcode = None
        # self.folda = Folda(self.e)
        self.recon = Recon(self.e)
        return None

    def update(self, repcode,  do_verbose=False):
        """update for a report"""
        e = self.e
        if repcode not in e.report:
            print("I don't know your report " + repcode)
            return False
        report = e.report[repcode]
        forpi_dir = report.dirs['forpi']
        report = e.report[repcode]
        forpi_dir = report.dirs['forpi']
        if not os.path.isdir(forpi_dir):
            print("forpi: this should not run with no {forpi_dir}",
                  file=sys.stderr)
            return
        child_dafus = self.plumi.dafus(repcode, no_mother=True)
        count_child = len(child_dafus)
        if count_child == 0:
            print("forpi: forpi.update should not have been invoqued",
                  file=sys.stderr)
            return None
        mother_dafus = self.mother_dafus(repcode)
        ## remove from the mother the child's issuedates
        for issuedate in list(mother_dafus):
            if issuedate in child_dafus:
                del mother_dafus[issuedate]
        count_mother = len(mother_dafus)
        # # delete the folder if there are too many child plumis
        if count_child > count_mother:
            print(f"forpi removes its folder {forpi_dir}")
            if os.path.isdir(forpi_dir):
                shutil.rmtree(forpi_dir)
            return None
        # # dafus that have been copied from the mother
        copid_dafus = self.folda.dafus(forpi_dir, ext=".txt.gz")
        count_copid = len(list(copid_dafus))
        # # general condition
        if count_mother - count_child == count_copid - 1:
            print("forpi is doing just fine!")
            return None
        if count_copid < count_mother - count_child + 1:
            #print(count_copid)
            #print(count_mother)
            #print(count_child)
            print("forpi does not have enough files",
                  file=sys.stderr)
            return None
        count_to_go = count_copid - count_mother + count_child - 1
        #if count_to_go != 1:
        #    print(f"forpi ought remove one file at a time, not {count_to_go}",
        #          file=sys.stderr)
        for date in list(copid_dafus)[-count_to_go:]:
            fufi = copid_dafus[date]
            if os.path.isfile(fufi):
                os.remove(fufi)
        # # remove the directory if no file is left.
        copid_dafus = self.folda.dafus(forpi_dir, ext=".txt.gz")
        count_copid = len(list(copid_dafus))
        if count_copid == 0:
            shutil.rmtree(forpi_dir)
        return None

    def create(self, repcode):
        e = self.e
        report = e.report[repcode]
        forpi_dir = report.dirs['forpi']
        if os.path.isdir(forpi_dir):
            # # this should not happen train invoques plumi.check mother
            # # only when the dafus are empty. If plaplu existing its
            # # files would have included in the plumi.dafus
            print(f"forpi: I see {forpi_dir}, no create.",
                  file=sys.stderr)
            return False
        os.makedirs(forpi_dir)
        # # takes the limit into accout, but not child plumis
        # # sets self.mother_repcode
        mother_dafus = self.mother_dafus(repcode)
        for issuedate in mother_dafus:
            shutil.copy(mother_dafus[issuedate], forpi_dir)
        return self.mother_repcode

    def mother_dafus(self, repcode):
        """takes into account the limit, but not child plumis"""
        mothers = self.recon.get_mothers(repcode)
        # # this should just have one element
        mother_repcode = list(mothers)[0]
        self.mother_repcode = mother_repcode
        mother_limit = mothers[mother_repcode]
        # print(f"forpi: mother is {mother_repcode} limit {mother_limit}")
        mother_dafus = self.plumi.dafus(mother_repcode)
        if mother_limit is None:
            return mother_dafus
        dafus = {}
        for issuedate in mother_dafus:
            if issuedate < mother_limit:
                continue
            dafus[issuedate] = mother_dafus[issuedate]
        return dafus
