from __future__ import absolute_import

# from carto.do_subscriptions import DOSubscriptionManager


def get_subscription_ids(credentials):
    purchased_datasets = fetch_subscriptions(credentials)
    purchased_dataset_ids = list(map(lambda pd: pd.id, purchased_datasets))
    return ','.join(["'" + id + "'" for id in purchased_dataset_ids])


def fetch_subscriptions(credentials):
    # if credentials:
    #     api_key_auth_client = credentials.get_api_key_auth_client()
    #     do_manager = DOSubscriptionManager(api_key_auth_client)
    #     if do_manager is not None:
    #         return do_manager.all()
    return []


def fetch_subscription_info(id):
    # TODO: implement
    return {
        'dataset_name': id,
        'price': '100.0',
        'url': 'http://carto.com'
    }


def trigger_subscription(id, credentials):
    # TODO: implement
    return 'OK'


def display_subscription_form(id, credentials):
    info = fetch_subscription_info(id)

    if is_ipython_notebook():
        display_subscription_form_notebook(id, info, credentials)
    else:
        display_subscription_form_cli()


def display_subscription_form_notebook(id, info, credentials):
    from IPython.display import display
    from ipywidgets.widgets import HTML, GridspecLayout, Button, Layout

    def create_expanded_button(description, button_style):
        return Button(description=description, button_style=button_style, layout=Layout(height='32px', width='176px'))

    message = '''
    <h3>Subscription contract</h3>
    You are about to subscribe to <b>{dataset_name}</b>.
    The cost of this dataset is <b>${price}</b>.
    If you want to proceed, a Request will be sent to CARTO who will
    order the data and load it into your account.
    This dataset is available for Instant Order for your organization,
    so it will automatically process the order and you will get inmediate access to the dataset.
    In order to proceed we need you to agree to the License of the dataset
    available at <b><a href="{url}" target="_blank">{url}</a></b>.
    <br>Do you want to proceed?
    '''.format(**info)
    text = HTML(message)

    button_yes = create_expanded_button('Yes', 'info')
    button_no = create_expanded_button('No', '')

    buttons = GridspecLayout(1, 5)
    buttons[0, 0] = button_yes
    buttons[0, 1] = button_no

    def disable_buttons():
        button_yes.disabled = True
        button_no.disabled = True

    def on_button_yes_clicked(b):
        disable_buttons()
        response = trigger_subscription('', '')
        if response:
            display(HTML('Yes'))
        else:
            display(HTML('No'))

    def on_button_no_clicked(b):
        disable_buttons()
        display(HTML('No'))

    button_yes.on_click(on_button_yes_clicked)
    button_no.on_click(on_button_no_clicked)

    display(text, buttons)


def display_subscription_form_cli():
    print('This method is not yet implemented in CLI')


def is_ipython_notebook():
    """
    Detect whether we are in a Jupyter notebook.
    """
    try:
        cfg = get_ipython().config
        if 'IPKernelApp' in cfg:
            return True
        else:
            return False
    except NameError:
        return False

@@ -33,16 +33,225 @@
 import%0A%0A
+# TODO: This file contains both the subscriptions endpoint functions%0A#       and the display form functions. Maybe we should consider to%0A#       separate this content, rename the file or refactor in classes.%0A%0A
 # from c
@@ -912,28 +912,18 @@
        '
+i
 d
-ataset_name
 ': id,%0A 
@@ -930,16 +930,34 @@
        '
+subscription_list_
 price': 
@@ -962,12 +962,10 @@
 : '1
-00.0
+95
 ',%0A 
@@ -976,19 +976,43 @@
    '
-url
+tos': '',%0A        'tos_link
 ': 'http
 ://c
@@ -1007,16 +1007,17 @@
 ': 'http
+s
 ://carto
@@ -1021,16 +1021,43 @@
 rto.com'
+,%0A        'type': 'dataset'
 %0A    %7D%0A%0A
@@ -1482,259 +1482,8 @@
 play
-%0A    from ipywidgets.widgets import HTML, GridspecLayout, Button, Layout%0A%0A    def create_expanded_button(description, button_style):%0A        return Button(description=description, button_style=button_style, layout=Layout(height='32px', width='176px'))
 %0A%0A  
@@ -1575,20 +1575,10 @@
 %3Cb%3E%7B
+i
 d
-ataset_name
 %7D%3C/b
@@ -1597,31 +1597,30 @@
 ost of this 
-dataset
+%7Btype%7D
  is %3Cb%3E$%7Bpri
@@ -1616,16 +1616,34 @@
 is %3Cb%3E$%7B
+subscription_list_
 price%7D%3C/
@@ -1774,23 +1774,22 @@
    This 
-dataset
+%7Btype%7D
  is avai
@@ -1923,23 +1923,22 @@
  to the 
-dataset
+%7Btype%7D
 .%0A    In
@@ -1998,23 +1998,22 @@
  of the 
-dataset
+%7Btype%7D
 %0A    ava
@@ -2035,19 +2035,24 @@
  href=%22%7B
-url
+tos_link
 %7D%22 targe
@@ -2066,13 +2066,17 @@
 nk%22%3E
-%7Burl%7D
+this link
 %3C/a%3E
@@ -2140,16 +2140,17 @@
 fo)%0A
+%0A
     text
  = H
@@ -2149,128 +2149,487 @@
 text
- = HTML(message)%0A%0A    button_yes = create_expanded_button('Yes', 'info')%0A    button_no = create_expanded_button('No', ''
+, buttons = _create_notebook_form(message)%0A%0A    display(text, buttons)%0A%0A%0Adef _create_notebook_form(message=''):%0A    from IPython.display import display%0A    from ipywidgets.widgets import HTML, Layout, Button, GridspecLayout%0A%0A    text = HTML(message)%0A%0A    button_yes = Button(%0A        description='Yes', button_style='info', layout=Layout(height='32px', width='176px'))%0A    button_no = Button(%0A        description='No', button_style='', layout=Layout(height='32px', width='176px')
 )%0A%0A 
@@ -3210,28 +3210,32 @@
 licked)%0A
+    
 %0A    
-display
+return 
 (text, b

Refactor subscription form