#!/usr/local/bin/python3
import sys
import os
from notion.client import NotionClient
from notion.block import PageBlock
from notion.block import TextBlock
from notion.block import ToggleBlock
from notion.markdown import markdown_to_notion
from datetime import datetime
import notion.records

from tzlocal import get_localzone

import notion
def call_load_page_chunk(self, page_id):

    if self._client.in_transaction():
        self._pages_to_refresh.append(page_id)
        return

    data = {
        "pageId": page_id,
        "limit": 100,
        "cursor": {"stack": []},
        "chunkNumber": 0,
        "verticalColumns": False,
    }

    recordmap = self._client.post("loadPageChunk", data).json()["recordMap"]

    self.store_recordmap(recordmap)

def call_query_collection(
    self,
    collection_id,
    collection_view_id,
    search="",
    type="table",
    aggregate=[],
    aggregations=[],
    filter={},
    sort=[],
    calendar_by="",
    group_by="",
):

    assert not (
        aggregate and aggregations
    ), "Use only one of `aggregate` or `aggregations` (old vs new format)"

    # convert singletons into lists if needed
    if isinstance(aggregate, dict):
        aggregate = [aggregate]
    if isinstance(sort, dict):
        sort = [sort]

    data = {
        "collectionId": collection_id,
        "collectionViewId": collection_view_id,
        "loader": {
            "limit": 1000000,
            "loadContentCover": True,
            "searchQuery": search,
            "userLocale": "en",
            "userTimeZone": str(get_localzone()),
            "type": type,
        },
        "query": {
            "aggregate": aggregate,
            "aggregations": aggregations,
            "filter": filter,
            "sort": sort,
        },
    }

    response = self._client.post("queryCollection", data).json()

    self.store_recordmap(response["recordMap"])

    return response["result"]

def search_pages_with_parent(self, parent_id, search=""):
    data = {
        "query": search,
        "parentId": parent_id,
        "limit": 100,
        "spaceId": self.current_space.id,
    }
    response = self.post("searchPagesWithParent", data).json()
    self._store.store_recordmap(response["recordMap"])
    return response["results"]

notion.store.RecordStore.call_load_page_chunk = call_load_page_chunk
notion.store.RecordStore.call_query_collection = call_query_collection
notion.client.NotionClient.search_pages_with_parent = search_pages_with_parent



# Build the content
fileThatContainsChanges = open(sys.argv[1], "r")
changes = fileThatContainsChanges.read().splitlines()
changesLength = len(changes)

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
description = ""
for changeIndex in range(changesLength):
	tempDesc = ""
	if changeIndex == 0 or not changes[changeIndex]:
		continue
	if changes[changeIndex] and changes[changeIndex][0] == "*":
		tempDesc = changes[changeIndex][:1] + "&nbsp;" + changes[changeIndex][1:] + '\r'
	else:
		tempDesc = changes[changeIndex] + '\n'
	description = description + tempDesc

terminalStream = os.popen('git status -s')
fileschanged = terminalStream.read()
numberOfFilesChanged = len(fileschanged.splitlines())

# Notion Section
token_v2 = 'TOKEN'
client = NotionClient(token_v2=token_v2)

#Url of the commit table.
url = "URL"
cv = client.get_collection_view(url, force_refresh=True)



row = cv.collection.add_row()
row.title = changes[0]
row.description = description
row.project = ['PROJECTNAME']


block = client.get_block(row.id)
block.children.add_new(TextBlock, title=description)
toggle = block.children.add_new(ToggleBlock, title="__"+str(numberOfFilesChanged)+" File(s) changed__")
toggle.children.add_new(TextBlock, title=fileschanged)
