# -*- coding: utf-8 -*-
from openpyxl import Workbook, load_workbook

from ddans.native.hook import NHook
from ddans.native.system import NSystem
from ddans.native.time import NTime
from ddans.native.log import NLog


class Xlsx():

    @staticmethod
    def write_kv_excel(json: dict | str, excel_file: str):
        try:
            if json is None or excel_file is None or len(excel_file) <= 0:
                return

            if isinstance(json, dict):
                json_data = json
            elif isinstance(json, str) and NSystem.exists(json):
                json_data = NSystem.read_json(json)
            else:
                return
            NSystem.ensure_dir(excel_file)

            wb = Workbook()
            ws = wb.active

            keys = list(json_data.keys())
            for i in range(len(keys)):
                key = keys[i]
                text = json_data[key]
                ws.append([key, text])
            wb.save(excel_file)
        except Exception:
            pass

    @staticmethod
    def write_row_excel(rows: list[list], excel_file: str):
        try:
            if rows is None or excel_file is None or len(excel_file) <= 0:
                return False

            if NHook.is_instance(rows, list[list]):
                rows_data = rows
            else:
                return False
            NSystem.ensure_dir(excel_file)

            wb = Workbook()
            ws = wb.active
            for index in range(len(rows_data)):
                ws.append(rows_data[index])
            wb.save(excel_file)
            return True
        except Exception as e:
            print(f"{e}")
            return False

    @staticmethod
    def write_kv_json(excel: Workbook | str,
                      json_file: str,
                      key_index: int = 0,
                      value_index: int = 1):
        try:
            if excel is None or json_file is None or len(json_file) <= 0:
                return

            if isinstance(excel, Workbook):
                wb = excel
            elif isinstance(excel, str) and NSystem.exists(excel):
                wb = load_workbook(excel)
            else:
                return

            NSystem.ensure_dir(json_file)
            ws = wb.active
            result = {}
            for rows in ws:
                key = rows[key_index].value
                value = rows[value_index].value
                if NHook.isvalid_str(key.strip()) and NHook.isvalid(value):
                    result[key] = value.rstrip('\n')

            jsonData = {
                key: value
                for key, value in result.items() if NHook.isvalid_str(value)
            }
            NSystem.write_json(jsonData, json_file)
        except Exception:
            pass

    @staticmethod
    def write_col_json(excel: Workbook | str, dir: str):
        try:
            if excel is None or dir is None or len(dir) <= 0:
                return

            if isinstance(excel, Workbook):
                wb = excel
            elif isinstance(excel, str) and NSystem.exists(excel):
                wb = load_workbook(excel)
            else:
                return

            ws = wb.active

            max_column = ws.max_column
            names = []
            jsonLists = [{}] * max_column
            for index, row in enumerate(ws):
                key = row[0].value
                if not NHook.isvalid_str(key.strip()):
                    continue
                values = [x.value or '' for x in row]
                if index == 0:
                    names = values
                else:
                    for idx, value in enumerate(values):
                        json = jsonLists[idx] or {}
                        if not NHook.isvalid_str(value):
                            continue
                        json[key] = value.rstrip('\n')
                        jsonLists[idx] = json

            for idx in range(len(names)):
                name = names[idx]
                if not NHook.isvalid_str(name):
                    continue
                if idx >= max_column:
                    break
                json = jsonLists[idx]
                if json is None:
                    continue
                json_file = NSystem.get_full_path(
                    dir, f"{name}_{NTime.format(format='%Y%m%d')}.json")
                NSystem.ensure_dir(json_file)
                jsonData = {
                    key: value
                    for key, value in json.items() if NHook.isvalid_str(value)
                }
                ret = NSystem.write_json(jsonData, json_file)
                if ret:
                    NLog.success(f"{json_file}")
        except Exception:
            pass
