# Custom installed lib imports
import rfeed

# Standard lib imports
import collections
import datetime
import os
import re
import subprocess
import urllib


BASE_URL = "http://alkanero.com"
POST_TEMPLATE = open("posts/template_post.html").read()
CSS=open("assets/normalize_purified.css").read()
MATHJAX_CDN="<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>"

def get_post_url(title):
    return title.lower().replace(
        " ", "_").replace("?", "").replace(
            ",", "") + ".html"

# From SO https://stackoverflow.com/questions/4389572/how-to-fetch-a-non-ascii-url-with-python-urlopen:
def urlEncodeNonAscii(b):
    return re.sub('[\x80-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), b)

def iriToUri(iri):
    parts= urllib.parse.urlparse(iri)
    return urllib.parse.urlunparse(
        part if parti==1 else urlEncodeNonAscii(part)
        for parti, part in enumerate(parts)
    )

def build_feed(posts):
  def build_rfeed_item(post):
    link = iriToUri(BASE_URL + "/posts/" + get_post_url(post.title))
    return rfeed.Item(
        title = post.title,
        link = link,
        description = post.description,
        author = "alex@email_som_inte_funkar.com",
        guid = rfeed.Guid(link),
        pubDate = datetime.datetime(post.date.year, post.date.month, post.date.day,
                                    00, 00))

  return rfeed.Feed(
    title = "Alkanero",
    link = BASE_URL,
    description = "Ställe på internet där Alex halv-anonymt skriver av sig",
    language = "sv",
    lastBuildDate = datetime.datetime.now(),
    items = [build_rfeed_item(post) for post in posts]
  )


def to_date_string(date):
  # Det här finns säkert i python-lib om man letar. Men locales är krångligt...
  swedish_months = ["januari", "februari", "mars", "april", "maj", "juni", "juli", "augusti",
                    "semptember", "oktober", "november", "december"]
  swedish_months_dict = {i+1: m for i, m in enumerate(swedish_months)}
  return "{d} {m} {y}".format(
      d=date.day, m=swedish_months_dict[date.month], y=date.year
  )

def build_post(post):
    # title = post.title
    # description = post.description
    # date = post.date
    # content_markdown_file = post.content_markdown_file
    # filename = get_post_url(title)

    pandoc_args = ["pandoc",
                   post.content_markdown_file,
                   # "--from", "markdown+tex_math_dollars+raw_tex+tex_math_single_backslash",
                   # "--pdf-engine=pdflatex",
                   "--mathjax",
                   "--verbose",
                   "-o",
                   "tmp.html"
    ]
    # print("Calling PANDOC with ARGS:")
    # print(*pandoc_args)
    subprocess.call(pandoc_args)
    content_html = open("tmp.html", "r").read()
    subprocess.call(["rm", "tmp.html"])

    post_path = "posts/" + get_post_url(post.title)

    with open(post_path, "w") as f:
        f.write(POST_TEMPLATE.format(
            description=post.description,
            title=post.title,
            date=to_date_string(post.date),
            posts_url=os.path.join("/", post_path),
            article_content=content_html,
            css=CSS,
            maybe_math=(MATHJAX_CDN if post.math else ""),
            maybe_custom_html = (open(post.custom_html).read() if post.custom_html else ""),
            some_day_later_XML=""
        ))

ARTICLE_LIST_ENTRY_TEMPLATE="""
<li class="article-list-item reveal">
      <a href="posts/{posts_url}" title="Content content">
        <h5>
          {title}
        </h5>
      </a>
      <p>{description}</p>
      <div class="article-list-footer">
        <span class="article-list-date">
          {date}
        </span>
        <span class="article-list-divider">-</span>
      </div>
    </li>
"""

ARTICLE_TEMPLATE=open("main_template.html", "r").read()

## Every post is a (title/discription/date) triple
def build_main(posts):
    article_list = "".join(
        ARTICLE_LIST_ENTRY_TEMPLATE.format(
            posts_url=get_post_url(post.title),
            title=post.title,
            description=post.description,
            date=to_date_string(post.date)
        )
        for post in posts
    )
    with open("test.html", "w") as f:
        f.write(ARTICLE_TEMPLATE.format(
            article_list=article_list,
            css=CSS
        ))

def generate_rss_xml(posts):
  with open("feed.xml", "w") as f:
    f.write(build_feed(posts).rss())

Post = collections.namedtuple("Post", "title, description, date, content_markdown_file, math, custom_html")
Post.__new__.__defaults__ = (False, False) # Applies to the last vars 'math' and 'custom_html'

posts = [
           Post(title="Statens budget 2020",
                description="Interaktiv sida som slumpar budgetposter.",
                date=datetime.date(2019, 10, 9),
                content_markdown_file="posts/budgetposter.md",
                custom_html="posts/budgetposter_interaktiv.html"
           ),
           Post(title="Peter Lundgren och klimatet",
                description="Den här är fortfarande lite halvfärdig. Sammanfattning kommer sen kanske.",
                date=datetime.date(2019, 7, 28),
                content_markdown_file="posts/lundgren_klimat.md",
                math=True
           ),

           # Post(title="Lundgren och klimatet statistik",
           #      description="Kommer sen kanske",
           #      date=datetime.date(2019, 7, 28),
           #      content_markdown_file="posts/lundgren_klimat_statistik_slask.md",
           #      math=True
           # ),

           Post(title="Project Euler-problem",
                description="Matterendering och ett matte/programmeringsproblem",
                date=datetime.date(2019, 7, 24),
                content_markdown_file="posts/euler.md",
                math=True,
           ),
           Post(title="RSS-flöde",
                description="Kort om att lägga till RSS-flöden",
                date=datetime.date(2019, 6, 25), #"25 juni 2019",
                content_markdown_file="posts/rss_flöde.md"),
           Post(title="Stöd för formler",
                description="Kort om att lägga till LaTeX",
                date=datetime.date(2019, 6, 25), #"25 juni 2019",
                math=True,
                content_markdown_file="posts/test_math.md"),
           

          Post(title="Blev Liberalerna räddade av regnet?",
               description="",
               date=datetime.date(2019, 5, 27), #"27 maj 2019",
               content_markdown_file="posts/blev_L_räddade_av_regnet.md"),

          Post(title="Ordinary Men av Christopher Browning",
               description="Jag har läst en känd fackbok och vill skriva om den.",
               date=datetime.date(2019, 1, 20), # "20 januari 2019",
               content_markdown_file="posts/ordinary_men.md"),
          Post(title="Viktors Val av Viktor Barth-Kron",
               description=("Viktor Barth-Kron skriver om "
                            "nutidspolitik i Viktors Val. Jag går igenom "
                            " sånt som har med migrationsdebatten att göra."),
               date=datetime.date(2018, 9, 22), #"22 september 2018",
               content_markdown_file="posts/viktors_val.md" ),
          Post(title="Kuriosa om det svenska valsystemet",
               date=datetime.date(2018, 9, 6), #"6 september 2018",
               content_markdown_file="posts/fusk_i_svenska_valsystemet.md",
               description="Några sätt som det svenska valsystemet kan utnyttjas "
               "för valfusk"
          ),
          Post(title="Hur extrem är extremsommaren?",
               date=datetime.date(2018, 9, 5), # "5 september 2018",
               content_markdown_file="posts/det_varma_vädret.md",
               description="Jag försöker reda ut hur extrem extremvärmen juli 2018 är. Med "
               "hjälp av statistik."
          ),
          Post(title="Amazon Command Line Interface",
               date=datetime.date(2018, 9, 3), #"3 september 2018",
               content_markdown_file="posts/amazon_cli.md",
               description="Hur man snabbt laddar upp ändringar med Amazon CLI."
          ),
          Post(title="Scripts för webbsidan",
               description="Scriptsen som klistrar ihop webbsidan.",
               date=datetime.date(2018, 9, 2), #"2 september 2018",
               content_markdown_file="posts/den_har_webbsidan_scripts.md"
          ),
          Post(title="Webbsida på en halv dag för 14 dollar",
               description="Hur den här webbsidan är byggd.",
               date=datetime.date(2018, 9, 2), #"2 september 2018",
               content_markdown_file="posts/den_har_webbsidan.md"
          ),
]


# build_post(
#     title=tmp_post.title,
#     description=tmp_post.description,
#     date=tmp_post.date,
#     content_markdown_file=tmp_post.content_markdown_file
# )

if __name__ == "__main__":
  for post in posts:
      build_post(post
                 # title=post.title,
                 # description=post.description,
                 # date=post.date,
                 # content_markdown_file=post.content_markdown_file
      )


  build_main(posts)

  #print("RSS below:")
  generate_rss_xml(posts)
