"""admin tasks for reports, a most boring module"""
import os
import sys
import shutil

import docing
import filer

from blata import Blata
from doker import Doker
from recon import Recon
from staff import Staff
from xpafs import Xpafs


class Adrep:

    def __init__(self, erimp, do_verbose=False):
        self.e = erimp
        self.do_verbose = do_verbose
        self.recon = Recon(erimp)
        self.blata = Blata(erimp)
        self.doker = Doker(erimp)
        self.staff = Staff(erimp)
        self.xpafs = Xpafs(erimp)
        return None

    def close(self, repcode, do_remove=False):
        if self.recon.is_it_enabled(repcode):
            print(f"{repcode} is still enabled")
            return False
        something_done = False
        doc = self.recon.doc(repcode, add_state=[])
        editor_xp = '/a:collection/a:haseditor'
        editors = self.xpafs.run(doc, editor_xp)
        if len(editors) > 1:
            print("FixMe: adrep can't handle several editors", file=sys.stderr)
            return False
        last_editor = editors[-1]
        jurfi_xp = './a:person | ./a:organization'
        editor_jurfis = self.xpafs.run(last_editor, jurfi_xp)
        if len(editor_jurfis) == 0:
            print(f"adrep: no editor in {repcode}",
                  file=sys.stderr)
            sys.exit()
            return False
        last_editor_jurfi = self.xpafs.run(last_editor, jurfi_xp)[0]
        jurfi = docing.show(last_editor_jurfi)
        stid = None
        if 'ref' in last_editor_jurfi.attrib:
            stid = last_editor_jurfi.attrib['ref']
        elif 'id' in last_editor_jurfi.attrib:
            stid = last_editor_jurfi.attrib['id']
        else:
            print("adrep don't see a staff for")
            print(jurfi)
        avail_fufi = self.recon.fufi(repcode)
        avail_doc = filer.parse_lax(avail_fufi)
        if avail_doc is None:
            print(f"adrep don't see the avail_doc for {repcode}",
                  file=sys.stderr)
            return False
        editor_xp = '/a:collection/a:haseditor'
        editors = self.xpafs.run(avail_doc, editor_xp)
        if len(editors) > 1:
            print("FixMe: adrep can't handle several editors",
                  file=sys.stderr)
            return False
        if len(editors) == 0:
            print(f"adrep sees no editor in {avail_fufi}",
                  file=sys.stderr)
            return False
        editor_ele = editors[0]
        dates = self.sent_dates(repcode)
        # # last date first
        firs_date = dates[-1]
        last_date = dates[0]
        do_i_save = self.doker.add_span(editor_ele, firs_date, last_date)
        if do_i_save:
            print(f"adrep saves {avail_fufi}")
            something_done = True
        filer.install_xml(avail_doc, avail_fufi)
        if stid is None:
            print(f"adrep: {repcode} does not use staff")
            return False
        staff_fufi = self.staff.fufi(stid)
        if not os.path.isfile(staff_fufi):
            print(f"adrep have not {staff_fufi}")
            return False
        staff_doc = filer.parse_lax(self.staff.fufi(stid))
        xp = f"/a:person/a:iseditorof[a:collection/@ref='{repcode}']"
        edi_ele = self.xpafs.one(staff_doc, xp)
        # # again this does not work if there are several editors who worked on
        # # the report. adrept will set the wrong data
        do_i_save = self.doker.add_span(edi_ele, firs_date, last_date)
        if do_i_save:
            print(f"adrep saves {staff_fufi}")
            something_done = True
            filer.install_xml(staff_doc, staff_fufi)
        opt_fudi = self.opt_dir(repcode)
        if os.path.isdir(opt_fudi):
            if not do_remove:
                print(f"adrep sees {opt_fudi}, use -r to remove")
            else:
                print(f"adrep removes {opt_fudi}")
                something_done = True
                shutil.rmtree(opt_fudi)
        return something_done

    def close_all(self, do_remove=False):
        """was done to clear backlog, should not be used"""
        for repcode in self.e.dead:
            dates = self.sent_dates(repcode)
            if dates is None:
                print(f"adrep: {repcode} has no sent_dates")
                continue
            # # last date first
            firs_date = dates[-1]
            last_date = dates[0]
            something_done = self.close(repcode, do_remove=do_remove)
            if something_done is False:
                result = ' unchanged'
            else:
                result = ' done'
            print(repcode + ' ' + firs_date + ' ' + last_date + result)
            if something_done:
                self.blata.weris_report(repcode)

    def opt_dir(self, repcode):
        opt_dir = self.e.dirs['reports'] + '/' + repcode + '/opt'
        return opt_dir

    def sent_dates(self, repcode, do_remove=False):
        sent_fudi = self.e.report[repcode].dirs['sent']
        if self.e.folda.by_dates(sent_fudi) is None:
            return None
            print(repcode)
            quit()
        dates = list(self.folda.by_dates(sent_fudi).keys())
        return dates
