import pyperclip
import json
import subprocess
import requests
import pandas as pd
import math
import inspect
import os
from pathlib import Path

#pyperclip.copy("Your text goes here")
#text = pyperclip.paste()

key='username=0cd67f84-268e-4238-a95f-ac3f02737a19'


def process_data(data):
    if isinstance(data, pd.DataFrame):
        data = to_list(data)

    return data
    
def is_nan(val):
    return val != val

def to_list(data):
    list1 = data.to_dict(orient='records')
    list2 = []
    for item in list1:
        nitem = {}
        list2.append(nitem)
        for key in item:
            key_str = str(key)
            value = item[key]
            if is_nan(value): value = None
            if key[0] == 'Date': 
                iso_string = value.isoformat()
                split1 = iso_string.split('T')
                value = split1[0]
            nitem[key_str] = value
        pass
    return list2

'''
EXAMPLE

TO SAVE THE DATA ORGINALLY

data = [{'test':7}]
#id = dv.post_data(data=data, name='test-python-data.json')
#print(id)

THEN TO UPDATE THE DATA - USE THE PROVIDED ID

dv.post_data(data=data, id='d1476ef5-1d25-4956-8784-dfbef479688f.json')


'''

def post_data(*, data, id=None, folderid=None, name=None):

    global key
    url = 'https://davinci-net.com/post-media/'
    #url = 'http://localhost/post-media/'
    #payload = {'name': 'Alice', 'role': 'admin'}

    '''custom_headers = {
        "User-Agent": "my-app/0.0.1",
        "Authorization": "Bearer YOUR_TOKEN_HERE",
        "Content-Type": "application/json"
    }'''

    custom_headers = {
        "Authorization": key,
    }

    # Sending JSON data
    #response = requests.post(url, headers=custom_headers,json=payload)

    obj = {
        "content":json.dumps(data),
    }
    if id != None: obj['id'] = id
    if folderid != None: obj['folderid'] = folderid
    if name != None: obj['name'] = name

    response = requests.post(url, headers=custom_headers,json=obj)

    # Handle the server response
    print(f"Status Code: {response.status_code}")
    split = response.text.split('=')
    return split[1]
    #return response.text
   

open_browser1 = True
def open_browser(bool):
    open_browser1 = bool
    pass

def reset():
    pyperclip.copy('')
    pass

def open(url):
    if open_browser1 == False:return
    # Windows path for Chrome - adjust if you installed it elsewhere
    chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"

    # For macOS, typically it's just: chrome_path = "open"
    # For Linux, it might be: chrome_path = "/usr/bin/google-chrome"

    # Open the URL in a detached subprocess
    subprocess.Popen([chrome_path, url])
    pass

def get_data(data, name="data"):
    config = {
  "body": {
    "data": json.dumps(data),
    "config": {
      "format": "json",
      "headers": False
    }
  },
  "name": name,
  "url": "/app/data/v1.0.0/embed.mjs",
  "app": "/app/data/v1.0.0/data.mjs",
  "export": {
    "category": {}
  }
}
    config['export'] = name 
    return config

from pathlib import Path
def deploy():
    
    directory_path = Path('.')
    # Use Path(".") for the current working directory, or specify a path like Path("/path/to/dir")
    files = [f for f in Path(".").iterdir() if f.is_file()]
    files2 = [str(entry) for entry in directory_path.rglob('*') if entry.is_file()]
    files2 = list(map(lambda x: x.replace('\\','/'),files2))

    parent = exclude_path()
    def filter1(path):
        split = path.split('/')
        if split[0] == '.env': return False 
        if split[0] == '.venv': return False 
        if '__' in path: return False
        split2 = path.split('.')
        extension = split2[len(split2)-1]
        if extension != 'py':return False
        if path == parent: return False
        return True

    files2 = list(filter(filter1, files2))
    configs = list(map(lambda x:get_python_config(x), files2))
    pyperclip.copy(json.dumps(configs))
    open('https://davinci-net.com/desktop/?_clipboard=true')
    pass

def get_python_config(path):
    content = Path('./'+path).read_text(encoding="utf-8")
    config = {
        "name":path,
        "body":{
            "script":content,
            "config":{
                "lib":True
            }
        },
        "url":'/app/python/v1.0.0/ctrl.mjs'
    }
    return config



def exclude_path():

    stack = inspect.stack()
    # Index 1 is the immediate caller in the execution stack
    caller_frame = inspect.stack()[2]
    
    # Get the raw filename/path from the frame
    caller_filename = caller_frame.filename

    caller_filename = caller_filename.replace('\\','/')
    split = caller_filename.split('/')
    return split[len(split)-1]
    
    # Convert it to an absolute path
    caller_absolute_path = os.path.abspath(caller_filename)
    
    print(f"Called by file located at: {caller_absolute_path}")

def data(data, name, url):
    if isinstance(data, list):
        configs = []
        pass 

    config = get_data(data, name)
    pyperclip.copy(json.dumps(config))
    if '?' in url:
        url += '&_clipboard=true'
    else: url += '?_clipboard=true'
    open(url)
    pass

def get_table(dataname):
    config = {
      "body": {
        "config": {
          "sortable": True,
          "filterable": True,
          "altrows": True,
          "columnsresize": True,
          "defaultwidth": "160px",
          "data": dataname
        },
        "style": '''#COMPONENT-ID{
	height:400px;
}
'''
      },
      "name": dataname+'-table',
      "url": "/app/view-data/v1.0.0/ctrl.mjs",
      "id": "iYpONSTa8-hmA9-Bqev-uDZK-36Xmg9dvTssF",
      "imports": [
        "category"
      ]}
    return config
    pass

def append(items):
    
    list = []
    try:
        text = pyperclip.paste()
        list = json.loads(text)
    except Exception as e:
        pass

    for item in items:list.append(item)
    pyperclip.copy(json.dumps(list))
    pass

def table(data, name='data'):
    data = process_data(data)
    dconfig = get_data(data, name)
    tconfig = get_table(name)
    append([dconfig, tconfig])
    open('https://davinci-net.com/page.html?_clipboard=true')
    pass

def dtable(data, name='data'):
    
    dconfig = get_data(data, name)
    tconfig = get_table(name)
    append([dconfig, tconfig])
    open('https://davinci-net.com/desktop/')
    pass




def linechart(data, series, name='data'):
    data = process_data(data)
    dconfig = get_data(data, name)
    config =  {
      "name": "line chart",
      "body": {
        "config": {
          "highchart": {
            "chart": {
              "type": "line"
            },
            "xAxis": {
              "title": {
                "text": ""
              }
            },
            "yAxis": {
              "title": {
                "text": ""
              }
            },
            "title": {
              "text": ""
            },
            "subtitle": {
              "text": ""
            },
            "tooltip": {},
            "legend": {
              "layout": "vertical",
              "align": "right",
              "verticalAlign": "top",
              "borderWidth": 0
            },
            "series": [
             
            ]
          }
        },
        "style": '''#COMPONENT-ID{
	border:solid;
	border-width:1px;
	border-color:lightgrey;
	height:400px;
}
'''
      },
      "url": "/app/highcharts/v1.0.0/ctrl.mjs",
      "site": "/home/documentation/template.html?url=/ctrls/highcharts/highlinechart/v1.0.0/site/doc.js",
      "id": "iEZDN4QQu-pCMJ-H2Dk-ZyYE-JPVH9sJfxxNb",
      "import": {
        "Fixed Timeseries": {}
      },
      "imports": [
        "Fixed Timeseries"
      ]
    }

    serieslist = config['body']['config']['highchart']['series']
    if isinstance(series, str):
        item = {
            'data':name,
            'type':'line',
            'properties':[series]
        }
        serieslist.append(item)
        pass
    else:
        for item in series:
            if isinstance(item, str):
                item = {'properties':[item]}
            item['data'] = name
            item['type'] = 'line'
            serieslist.append(item)
            pass

    append([dconfig, config])
    open('https://davinci-net.com/page.html?_clipboard=true')
    pass

