#-*- coding: utf-8 -*-

import json
import os
import shutil
import gzip
import time
from modules.colors import *
from datetime import datetime
from pathlib import Path

path = Path(__file__).resolve().parent

days_path = str(path)+"/assets/days/"
users_path = str(path)+"/users/"
logs_folder = str(path)+"/logs/"


def jsonSave(filename, value):
    with open(filename, 'w', encoding="utf-8") as f:
        json.dump(value, f, indent=4, ensure_ascii=False)
        f.close()

def jsonLoad(filename):
    with open(filename, 'r', encoding="utf-8") as f:
        value = json.load(f)
        f.close()
    return value


config = jsonLoad(f"{path}/config.json")

log_size = config["log_size"]
owner_id = config["owner_id"]


def nowtime():
    return f'{BBLACK}[{CYAN}{datetime.now().strftime("%H:%M:%S")}{BBLACK}]{RESET}'

def checkSize():
    global logs_folder, log_size
    
    i = 0

    while i < 2:
        try:
            log = os.stat(logs_folder + 'latest.log')

            if (log.st_size / 1024) > log_size:
                with open(logs_folder + 'latest.log', 'rb') as f_in:
                    with gzip.open(f'{logs_folder}{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.zip', 'wb') as f_out:
                        shutil.copyfileobj(f_in, f_out)
                            
                open(logs_folder + 'latest.log', 'w').close()
                
            i = 2

        except FileNotFoundError:
            
            try:
                log = open(logs_folder + 'latest.log', 'a')
                open(logs_folder + 'latest.log', 'a').close()
            except:
                try:
                    os.mkdir(logs_folder)
                    log = open(logs_folder + 'latest.log', 'a')
                    open(logs_folder + 'latest.log', 'a').close()
                except:
                    pass
            
            i += 1

def appendLog(message):
    global logs_folder

    checkSize()

    try:
        log = open(logs_folder + 'latest.log', 'a')
        open(logs_folder + 'latest.log', 'a').close()
    except:
        try:
            os.mkdir(logs_folder)
            log = open(logs_folder + 'latest.log', 'a')
            open(logs_folder + 'latest.log', 'a').close()
        except:
            time.sleep(2)
            print('Log file could not be created')
            return
            
    log.write(f'[{datetime.now().strftime("%H:%M:%S | %d.%m.%Y")}] {message}\n')
        
    log.close()


def string(key: str, *args: str, userlocale="uk"):
    locales = jsonLoad("strings.json")
    strings = locales[userlocale]
    string = strings
    for dict_key in args:
        string = string[dict_key]
    return string[key]


def userSet(userid, key: str, value):
    database = jsonLoad("data/database.json")
    if str(userid) not in database:
        database[str(userid)] = {}
    database[str(userid)][key] = value
    jsonSave("data/database.json", database)

def userReset(userid, key: str):
    database = jsonLoad("data/database.json")
    del database[str(userid)][key]
    jsonSave("data/database.json", database)

def userGet(userid, key: str):
    try:
        return jsonLoad("data/database.json")[str(userid)][key]
    except KeyError:
        return None
    except FileNotFoundError:
        return None