#!/usr/bin/env python3

import sys
import os
import asyncio
from main import main, readDBTable, listDBTable
from mainFlats import main as mainFlats, returnArticleContent
import urllib.parse
import glob
import json

async def loadMain():
    task = asyncio.create_task(parseQuery(sys.argv[1]))
    result = await task
    print(result.decode("utf-8"))


async def parseQuery(query):
    if 'dbRead' in query:
        tablepos = query.find('dbRead') + len('dbRead') + 1
        table = query[tablepos:]
        if '&' in table:
            table = table.split('&')[0]

        if table == 'tables':
            return "{}".format(listDBTable()).encode('utf-8')
        
        return "{}".format(readDBTable(table)).encode('utf-8')

    if 'soup' in query:
        if 'quick' in query:
            if 'flats' in query:
                return "{}".format(await mainFlats('quick')).encode('utf-8')    
            return "{}".format(await main('quick')).encode('utf-8')
        return "{}".format(await main()).encode('utf-8')
    
    if 'content' in query:
        if 'siId=' in query:
            if 'href=' in query:
                queryArray = query.split('/')
                siId = None
                href = None
                for queryPart in queryArray:
                    if queryPart.find('siId=') != -1:
                        siId = queryPart.split('=')[1]
                    if queryPart.find('href=') != -1:
                        href = query.split('/href=')[1]
                        if 'homegate' in href:
                            href = 'https://www.homegate.ch/rent/'+siId
                if siId != None and href != None:
                    return "{}".format(await returnArticleContent(siId, href)).encode('utf-8')

    if 'editConf' in query:
        reqFilePos = query.find('editConf') + len('editConf') + 1
        reqFile = query[reqFilePos:]
        if reqFile == 'showAll':
            configFiles = glob.glob('../data/*.conf')
            response = []
            for file in configFiles:
                fileBaseName = file.rsplit('/', 1)[-1]
                fileName = fileBaseName.split('.', 1)[0]
                response.append(fileName)
            response = json.dumps(response)
        else:
            fileBaseName = "../data/"+reqFile.replace('/', '')+".conf"
            if (os.path.isfile(fileBaseName)):
                f = open(fileBaseName, "r")
                response = f.read()
                f.close()


        return "{}".format(response).encode('utf-8')



if __name__ == '__main__':
    if len(sys.argv) == 2:
        asyncio.run(loadMain())