#!/usr/bin/env python
# coding=utf8

from gi.repository import Gtk, GLib
import requests

UI = """<?xml version="1.0"?>
<interface>
  <requires lib="gtk+" version="2.16"/>
  <!-- interface-naming-policy project-wide -->
  <object class="GtkWindow" id="main_window">
    <property name="default_width">640</property>
    <property name="default_height">550</property>
    <signal name="delete_event" handler="gtk_main_quit"/>
    <child>
      <object class="GtkVPaned" id="vpaned1">
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <child>
          <object class="GtkScrolledWindow" id="scrolledwindow1">
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="hscrollbar_policy">automatic</property>
            <property name="vscrollbar_policy">automatic</property>
            <child>
              <object class="GtkTreeView" id="classifiers_view">
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="model">classifiers_store</property>
                <property name="search_column">0</property>
                <child>
                  <object class="GtkTreeViewColumn" id="treeviewcolumn1">
                    <property name="title">Active</property>
                    <property name="clickable">True</property>
                    <property name="sort_column_id">0</property>
                    <child>
                      <object class="GtkCellRendererToggle" id="renderer_active"/>
                      <attributes>
                        <attribute name="active">0</attribute>
                      </attributes>
                    </child>
                  </object>
                </child>
                <child>
                  <object class="GtkTreeViewColumn" id="Classifiers">
                    <property name="title">column</property>
                    <property name="clickable">True</property>
                    <property name="sort_column_id">1</property>
                    <child>
                      <object class="GtkCellRendererText" id="renderer_text"/>
                      <attributes>
                        <attribute name="text">1</attribute>
                      </attributes>
                    </child>
                  </object>
                </child>
              </object>
            </child>
          </object>
          <packing>
            <property name="resize">True</property>
            <property name="shrink">True</property>
          </packing>
        </child>
        <child>
          <object class="GtkScrolledWindow" id="scrolledwindow2">
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="hscrollbar_policy">automatic</property>
            <property name="vscrollbar_policy">automatic</property>
            <child>
              <object class="GtkTextView" id="output">
                <property name="height_request">200</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
              </object>
            </child>
          </object>
          <packing>
            <property name="resize">False</property>
            <property name="shrink">True</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
  <object class="GtkListStore" id="classifiers_store">
    <columns>
      <!-- column-name active -->
      <column type="gboolean"/>
      <!-- column-name name -->
      <column type="gchararray"/>
    </columns>
  </object>
</interface>
"""


def reset_model():
    model = builder.get_object('classifiers_store')

    model.clear()

    # load data
    url = r'http://pypi.python.org/pypi?%3Aaction=list_classifiers'
    resp = requests.get(url)
    resp.raise_for_status()

    for line in resp.text.splitlines():
        model.append((False, line.strip()))


def on_cell_toggle(renderer, path):
    model = builder.get_object('classifiers_store')
    i = model.get_iter(path)

    # flip column 0, the "active" column
    model.set_value(i, 0, not model.get_value(i, 0))

    # update tree view
    chunks = ['classifiers=[']
    i = model.get_iter_first()
    while i is not None:
        if model.get_value(i, 0) is True:
            chunks.append("    '%s'," % model.get_value(i, 1))
        i = model.iter_next(i)
    chunks.append(']')

    builder.get_object('output').get_buffer().set_text('\n'.join(chunks))


if '__main__' == __name__:
    builder = Gtk.Builder()
    builder.add_from_string(UI)

    # load data
    reset_model()

    # set up GUI
    mw = builder.get_object('main_window')
    mw.connect('delete-event', lambda a, b: Gtk.main_quit())
    builder.get_object('renderer_active').connect('toggled', on_cell_toggle)
    GLib.set_application_name('PyPI classifiers selector 0.1')
    mw.show()
    Gtk.main()
