# -*- coding: utf-8 -*-
# pylint: disable=bad-continuation, too-few-public-methods
""" 'tidy' command.
"""
# Copyright ©  2015 1&1 Group <git@1and1.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, unicode_literals, print_function

import re

from rudiments.reamed import click

from .. import config, api


# Simple replacement rules, order is important!
REGEX_RULES = ((re.compile(_rule), _subst) for _rule, _subst in [
    # FosWiki: 'tok' spans in front of headers
    (r'(?<=<h.>)<span class="tok">&nbsp;</span>', ''),
    # FosWiki: Section edit icons at the end of headers
    (r' *<a href="[^"]+"><ac:image [^>]+><ri:url ri:value="[^"]+/EditChapterPlugin/pencil.png" ?/></ac:image></a>(?=</span></h)', ''),
    # FosWiki: "Edit Chapter Plugin" spans
    (r'(?<=<h.>)<span class="ecpHeading">([^<]+)</span>(?=</h.>)', r'\1'),
    # FosWiki: Residual leading whitespace in headers
    (r'(?<=<h.>) +', ''),
])


class ConfluencePage(object):
    """A page that holds enough state so it can be modified."""

    def __init__(self, cf, url, markup='storage'):
        """Load the given page."""
        self.url = url
        self.markup = markup
        self._data = cf.get(self.url, expand='body.' + self.markup)
        self.body = self._data.body.storage.value


@config.cli.command()
@click.option('-R', '--recursive', is_flag=True, default=False, help='Handle all descendants.')
@click.argument('pages', metavar='‹page-url›…', nargs=-1)
@click.pass_context
def tidy(ctx, pages, recursive=False):
    """Tidy pages after cut&paste migration from other wikis."""
    with api.context() as cf:
        for page_url in pages:
            try:
                page = ConfluencePage(cf, page_url)
            except api.ERRORS as cause:
                # Just log and otherwise ignore any errors
                click.serror("API ERROR: {}", cause)
            else:
                ctx.obj.log.info('%d attributes', len(page._data))
                #print(page._data)
                print(page.body)
                for rule, subst in REGEX_RULES:
                    page.body, count = rule.subn(subst, page.body)
                    if count:
                        ctx.obj.log.info('Replaced %d matches of %r', count, rule.pattern)
                print('')
                print(page.body)

@@ -777,16 +777,43 @@
 ort re%0A%0A
+from bunch import bunchify%0A
 from rud
@@ -1656,24 +1656,45 @@
 en page.%22%22%22%0A
+        self.cf = cf%0A
         self
@@ -1779,16 +1779,30 @@
 expand='
+space,version,
 body.' +
@@ -1854,22 +1854,1089 @@
 body
-.storage.value
+%5Bself.markup%5D.value%0A%0A    def update(self, body=None):%0A        %22%22%22Update a page's content.%22%22%22%0A        assert self.markup == 'storage', %22Cannot update non-storage page markup!%22%0A        if body is None:%0A            body = self.body%0A        if body == self._data.body%5Bself.markup%5D.value:%0A            return  # No changes%0A%0A        data = %7B%0A            #'id': self._data.id,%0A            'type': 'page',%0A            'space': %7B'key': self._data.space.key%7D,%0A            'title': self._data.title,%0A            'version': %7B'number': self._data.version.number + 1%7D,%0A            'body': %7B%0A                'storage': %7B%0A                    'value': body,%0A                    'representation': self.markup,%0A                %7D%0A            %7D,%0A            'expand': 'version',%0A        %7D%0A        response = self.cf.session.put(self._data._links.self, json=data)%0A        response.raise_for_status()%0A        ##page = response.json(); print(page)%0A        result = bunchify(response.json())%0A        self._data.body%5Bself.markup%5D.value = body%0A        self._data.version = result.version%0A        return result
 %0A%0A%0A@
@@ -3617,16 +3617,17 @@
         
+#
 #print(p
@@ -3632,24 +3632,29 @@
 (page._data)
+; xxx
 %0A           
@@ -3650,32 +3650,34 @@
                 
+##
 print(page.body)
@@ -3669,32 +3669,65 @@
 rint(page.body)%0A
+                body = page.body%0A
                 
@@ -3778,21 +3778,16 @@
         
-page.
 body, co
@@ -3809,21 +3809,16 @@
 (subst, 
-page.
 body)%0A  
@@ -3956,16 +3956,32 @@
     
+##
 print('
-'
+%5Cn' + page.body
 )%0A  
@@ -3994,25 +3994,166 @@
         
-print(page.body
+result = page.update(body)%0A                if result:%0A                    ctx.obj.log.info('Updated page#%7Bid%7D to version #%7Bversion.number%7D'.format(**result)
 )%0A

put back tidied page body