#! /usr/bin/env python3

#    Copyright 2016, 2020 Denis Salem
#
#    This file is part of VenC.
#
#    VenC is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    VenC is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with VenC.  If not, see <http://www.gnu.org/licenses/>.

import os
import yaml
import codecs
import shutil

from venc2.helpers import die
from venc2.helpers import notify
from venc2.datastore.entry import yield_entries_content
from venc2.l10n import messages

def replace_patterns(string):
    string = string.replace(".:Get::EntryID:.",".:GetEntryID:.")
    string = string.replace(".:Get::EntryName:.",".:GetEntryTitle:.")
    string = string.replace(".:Get::EntryMonth:.",".:GetEntryMonth:.")
    string = string.replace(".:Get::EntryYear:.",".:GetEntryYear:.")
    string = string.replace(".:Get::EntryDay:.",".:GetEntryDay:.")
    string = string.replace(".:Get::EntryHour:.",".:GetEntryHour:.")
    string = string.replace(".:Get::EntryMinute:.",".:GetEntryMinute:.")
    string = string.replace(".:Get::EntryCSS:",".:GetEntryMetadataIfExists::style:")

    string = string.replace(".:Get::AuthorName:.",".:GetAuthorName:.")
    string = string.replace(".:Get::BlogName:.",".:GetBlogName:.")
    string = string.replace(".:Get::BlogDescription:.",".:GetBlogDescription:.")
    string = string.replace(".:Get::BlogKeywords:.",".:GetBlogKeywords:.")
    string = string.replace(".:Get::AuthorDescription:.",".:GetAuthorDescription:.")
    string = string.replace(".:Get::License:.",".:GetBlogLicense:.")
    string = string.replace(".:Get::BlogUrl:.",".:GetBlogURL:.")
    string = string.replace(".:Get::BlogLanguage:.",".:GetBlogLanguage:.")
    string = string.replace(".:Get::AuthorEmail:.",".:GetAuthorEmail:.")
    string = string.replace(".:Get::RelativeOrigin:.",".:GetRelativeOrigin:.")
    string = string.replace(".:Get::RelativeLocation:.",".:GetRelativeLocation:.")
    string = string.replace(".:RecursiveFor::BlogCategories::",".:TreeForBlogCategories::")
    
    string = string.replace(".:Get::EntryUrl:.",".:GetEntryURL:.")
    string = string.replace(".:Get::EntryContent:.",".:GetEntryContent:.")
    string = string.replace(".:Get::EntryDate:.",".:GetEntryDate:.")
    string = string.replace(".:Get::EntryDateUrl:.",".:GetEntryDateURL:.")
    
    string = string.replace(".:For::EntryTags:",".:ForEntryTags:")
    string = string.replace(".:For::EntryAuthors:",".:ForEntryAuthors:")
    string = string.replace(".:For::BlogDates:",".:ForBlogArchives:")
    string = string.replace(".:PagesList:",".:ForPages:")
    string = string.replace("{0[tag]}", "{value}")
    string = string.replace("{0[categoryPath]}", "{path}")
    string = string.replace("{0[relativeOrigin]}", '')
    string = string.replace("{0[date]}", "{value}")
    string = string.replace("{0[author]}", "{value}")
    string = string.replace("{0[item]}", "{value}")
    string = string.replace("{0[pageUrl]}", "{path}")
    string = string.replace("{0[dateUrl]}", "{path}")
    string = string.replace("{0[count]}", "{count}")
    string = string.replace("{0[weight]}", "{weight}")
    string = string.replace("{0[destinationPageUrl]}", "{path}")
    string = string.replace("{0[pageNumber]}", "{page_number}")

    return string

def to_camel_case(name):
    chunks = name.split('_')
    if len(chunks) == 1:
        return name

    output = chunks[0].lower()
    
    for word in chunks[1:]:
        output += word.title()

    return output

''' Processing blog configuration '''
try:
    blog_configuration = yaml.load(
        open(os.getcwd()+"/blog_configuration.yaml",'r').read(),
        Loader=yaml.FullLoader
    )

except FileNotFoundError:
    die(messages.no_blog_configuration)

except PermissionError:
    die(messages.no_blog_configuration)
        
except yaml.scanner.ScannerError:
        die(messages.possible_malformed_blog_configuration)

for key in ["thread_order", "textEditor","rss_thread_lenght"]:
    try:
        blog_configuration.pop(key)

    except KeyError:
        pass


new_keys = {
    "text_editor":"nano",
    "reverse_thread_order" : True,
    "markup_language": "Markdown",
    "disable_threads": "",
    "disable_main_thread": False,
    "disable_archives": False,
    "disable_categories": False,
    "disable_chapters": True,
    "disable_single_entries": False,
    "path_encoding":"utf-8",
    "code_highlight_css_override":False,
    "server_port": 8888,
    "disable_rss_feed":False,
    "disable_atom_feed":False,
    "feed_lenght": 5,
    "sort_by":'id',
    "enable_jsonld": False,
    "enable_jsonp": False
}

new_path_keys = {
    "atom_file_name": "atom_feed.xml",
    "entries_sub_folders":"",
    "chapters_sub_folders":"chapters",
    "chapter_directory_name": "{chapter_name}",
    "categories_sub_folders":"",
    "dates_sub_folders":""
}

for key in new_keys.keys():
    if not key in blog_configuration.keys():
        blog_configuration[key] = new_keys[key]

if not "path" in blog_configuration.keys():
    blog_configuration["path"] = {}

for key in new_path_keys.keys():
    if not key in blog_configuration["path"].keys():
        blog_configuration["path"][key] = new_path_keys[key]

stream = codecs.open('blog_configuration.yaml', 'w',encoding="utf-8")
yaml.dump(blog_configuration, stream, default_flow_style=False, allow_unicode=True)

''' Processing entries '''

for entry_filename in yield_entries_content():
    raw_data = open(os.getcwd()+"/entries/"+entry_filename,'r').read()
    try:
        metadata = yaml.load(
            raw_data.split("---\n")[0],
            Loader=yaml.FullLoader
        )
        metadata["title"] = metadata.pop("entry_name")

    except yaml.scanner.ScannerError:
        die(messages.possible_malformed_entry.format(entry_filename))

    except KeyError:
        if not "title" in metadata.keys():
            die(messages.possible_malformed_entry.format(entry_filename))
        else:
            pass

    output = yaml.dump(metadata, default_flow_style=False, allow_unicode=True) + "\n---VENC-BEGIN-PREVIEW---\n---VENC-END-PREVIEW---\n"

    try:
        output += replace_patterns(raw_data.split("---\n")[1])
    
    except IndexError:
        notify(messages.empty_entry.format(entry_filename), "YELLOW")
    
    stream = codecs.open("entries/"+entry_filename,'w',encoding="utf-8")
    stream.write(output)

''' Processing chunks '''

for chunk in os.listdir("theme/chunks"):
    raw_data = open("theme/chunks/"+chunk,'r').read()
    stream = codecs.open("theme/chunks/"+chunk,'w',encoding="utf-8")
    update = replace_patterns(raw_data)
    stream.write(update)

for chunk in ["audio.html","video.html"]:
    shutil.copy(os.path.expanduser("~/.local/share/VenC/themes/dummy/chunks/"+chunk), "theme/chunks/"+chunk)

print("Done.")
