# import json
import logging
import os
from .c11_api import c11_api
from datetime import datetime


class c11_create:
    api: c11_api
    config = None
    log_dir = "C:/GlobalCube/Tasks/logs/c11"
    spec_dir = "C:/GlobalCube/System/OPTIMA/Report"

    def __init__(self, cfg, api=None):
        self.config = cfg
        self.api = api
        if api is None:
            self.api = c11_api().login()

        now = datetime.now().strftime('%Y%m%d_%H%M%S')
        prot_file = f"{self.log_dir}/create_{now}.log"
        os.makedirs(self.log_dir, exist_ok=True)
        logging.basicConfig(
            filename=prot_file,
            filemode='w',
            encoding='utf-8',
            level=logging.DEBUG,
            force=True
        )

    def create_path(self, path, recursive=False):
        if path.startswith('Team Content'):
            fullpath = f"{self.spec_dir}/{path}"
        else:
            pos = path.find('Team Content')
            fullpath = path
            path = fullpath[pos:]

        fullpath = os.path.abspath(fullpath)
        path = path.replace('\\', '/')

        if not os.path.exists(fullpath):
            logging.error(fullpath + ' does not exist!')
            return False

        folder = path if os.path.isdir(fullpath) else os.path.dirname(path)
        folder_id = self.create_folders(folder)
        if os.path.isfile(fullpath):
            self.create_report(folder_id, folder, fullpath)

    def create_folders(self, folder):
        folder_split = folder.split('/')
        folder_parents = ['/'.join(folder_split[:i]) for i in range(1, len(folder_split) + 1)]
        print(folder_parents)
        folders = self.api.get_folders()
        last_id = None
        for parent in folder_parents:
            parent_id = [f['id'] for f in folders if f['name'] == parent]
            if len(parent_id) > 0:
                last_id = parent_id.pop()
            else:
                last_id = self.api.create_folder(last_id, os.path.basename(parent))
        return last_id

    def create_report(self, folder_id, folder_name, fullpath):
        report_name = os.path.basename(fullpath)[:-4]
        reports = [r for r in self.api.get_reports_in_folder(folder_name) if r['name'] == report_name]
        if len(reports) == 0:
            self.api.create_report(folder_id, fullpath)
        else:
            self.api.update_report(reports[0], fullpath)


if __name__ == '__main__':
    create_api = c11_create()
    # pdf.export_folder('Team Content/Verkauf/1. Gesamtverkauf', 'PDF')
    # pdf.export_folder('Team Content/Aftersales/1. Service')
    create_api.create_path('Team Content/ReportOutput/Forderungen')
