#!/usr/bin/env python2.5

# Copyright 2008 bjweeks, MZMcBride
#Develop by Javad Yousefi // javad.y1@gmail.com

# This program 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.

# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

import operator
import wikipedia
import config
import datetime
import MySQLdb

report_title = u'ويكيبيديا:إحصاءات/نشاط الإداريين'
message=u"بوت التحديث"
site  = wikipedia.getSite("ar")
conn = MySQLdb.connect("arwiki.labsdb", db = site.dbName(),
                       user = config.db_username,
                       passwd = config.db_password)
cursor = conn.cursor()


def get_stats(typeOfLog, action):
    cursor.execute(u'''
        /* logactions.py SLOW_OK */
        SELECT
          user_name,
          COUNT(log_timestamp)
        FROM logging
        JOIN user
        ON user_id = log_user
        WHERE log_type = '%s'
        AND log_action = '%s'
        AND user_name IN (SELECT user_name FROM user_groups INNER JOIN user ON user_id = ug_user WHERE ug_group = 'sysop')
        GROUP BY log_user;
    ''' % (typeOfLog, action))
    data = cursor.fetchall ()
    print len (data)
    return data

query_list = [
    {'name': u'حذف',                 'short_name': 'DL', 'type': 'delete',     'action': 'delete'},
    {'name': u'استرجاع',               'short_name': 'UD', 'type': 'delete',     'action': 'restore'},
    {'name': u'إخفاء نسخة',        'short_name': 'RD', 'type': 'delete',     'action': 'revision'},
    {'name': u'Delete edit version (ED)',           'short_name': 'ED', 'type': 'delete',     'action': 'event'},
#    {'name': u'إخفاء نسخة (DS)',     'short_name': 'DS', 'type': 'suppress',   'action': 'delete'},
#    {'name': u'إظهار نسخة (RS)',     'short_name': 'RS', 'type': 'suppress',   'action': 'revision'},
#    {'name': u'Edit versoin hiding (ES)',        'short_name': 'ES', 'type': 'suppress',   'action': 'event'},
#    {'name': u'Username hiding (US)',     'short_name': 'US', 'type': 'suppress',   'action': 'reblock'},
    {'name': u'حماية',               'short_name': 'PT', 'type': 'protect',    'action': 'protect'},
    {'name': u'إزالة الحماية',             'short_name': 'UP', 'type': 'protect',    'action': 'unprotect'},
    {'name': u'تغيير الحماية',  'short_name': 'PM', 'type': 'protect',    'action': 'modify'},
    {'name': u'منع',                    'short_name': 'BL', 'type': 'block',      'action': 'block'},
    {'name': u'رفع المنع',                  'short_name': 'UB', 'type': 'block',      'action': 'unblock'},
    {'name': u'تغيير مدة المنع',       'short_name': 'BM', 'type': 'block',      'action': 'reblock'},
    {'name': u'تغيير اسم المستخدم',              'short_name': 'UR', 'type': 'renameuser', 'action': 'renameuser'},
    {'name': u'تغيير صلاحيات', 'short_name': 'RM', 'type': 'rights',     'action': 'rights'},
#    {'name': u'Adding to white list (WL)',             'short_name': 'WL', 'type': 'gblblock',   'action': 'whitelist'},
#    {'name': u'Removing from white list (DW)',          'short_name': 'DW', 'type': 'gblblock',   'action': 'dwhitelist'},
#    {'name': 'تعديل مرشح الإساءة (AM)', 'short_name': 'AM', 'type': 'abusefilte', 'action': 'modify'}
]
user_stats = {}

for query in query_list:
    stats_query = get_stats(query['type'], query['action'])
    query['len'] = len(stats_query)
    for row in stats_query:
        user = unicode(row[0], 'utf-8')
        count = row[1]
        if user not in user_stats:
            user_stats[user] = {query['name']: count}
        else:
            user_stats[user][query['name']] = count

output = u''
report_template = u'\n__NOTOC__\n'
pagetop=u'{{إحصاء}}\n'
pagetop+=u'\n<center>\n'
pagetop+=u'<div style="background: #E5E4E2; padding: 0.5em; font-family: Traditional Arabic; font-size: 130%;  -moz-border-radius: 0.3em; border-radius: 0.3em;">'
pagetop+=u"\n'''تعرض هذه الصفحة قائمة الإحصاءات المتعلقة بنشاط الإداريين.'''\n"
pagetop+=u"\n'''قام [[مستخدم:{{نسخ:Currentuser}}|{{نسخ:Currentuser}}]] بتحديث هذه القائمة في :''''' ~~~~~ '''"
pagetop+=u'\n</div>'
pagetop+=u'</center>'
pagetop+=u'<div style="background: #E5E4E2; padding: 0.5em;   -moz-border-radius: 0.3em; border-radius: 0.3em;">'
pagedown=u'<small>(DL:حذف,UD:استرجاع,RD:إخفاء نسخة,PT:حماية,UP:إزالة الحماية,PM:تغيير الحماية,BL:منع,UB:رفع المنع,BM:تغيير مدة المنع,RM:تغيير صلاحيات)</small>\n[[تصنيف:إحصاءات ويكيبيديا]]'
pagedown+=u'\n</div>'
pagedown+=u'\n</div>'
report_template += u"\n%s"

table_template = u'''
<div class="NavFrame collapsed" style="text-align:right">
  <div class="NavHead" style="font-size: 10pt;">&nbsp; %s </div>
    <div class="NavContent">
<div style="text-align: right;">
{| class="wikitable sortable" style="width:23em;"
|- style="white-space:nowrap;"
! رقم
! المستخدم
! عدد
|-
%s
|}
الإحصاءات الكاملة متوفرة في [[{{FULLPAGENAME}}#الإحصاءات الكاملة|الأسفل]].\n
</div>
</div>
</div>
'''

for query in query_list:
    stat_dict = {}
    for user,stats in user_stats.iteritems():
        if query['name'] in stats:
            stat_dict[user] = stats[query['name']]
    stats = sorted(stat_dict.iteritems(), key=operator.itemgetter(1), reverse=True)[0:50]
    rows = []
    i = 1
    for user, count in stats:
        jy=str(i).replace(u'0',u'0')
        count2=str(count).replace(u'0',u'0')
        rows.append(u'''| %s\n| [[مستخدم:%s|%s]]\n| %s\n|-''' % (jy, user, user, count2))
        i += 1
    output += table_template % (query['name'], '\n'.join(rows))
    if query['len'] > 1:
        output += u" "

master_table_template = u'''
== الإحصاءات الكاملة ==

{| class="wikitable sortable" style="width:100%%; margin:auto;"
|- style="white-space:nowrap;"
! رقم
! المستخدم
%s
! المجموع
|-
%s class="sortbottom"
! colspan="2" | المجموع
%s
|}
'''

new_query_list = []

for query in query_list:
    if query['len'] > 20:
        new_query_list.append(query)

query_list = new_query_list

rows = []
totals = dict([(query['name'], 0) for query in query_list])
totals['total'] = 0
i = 1
user_stats_sorted = sorted(user_stats.iteritems(), key=operator.itemgetter(0))
for user,stats in user_stats_sorted:
    row = []
    total = 0
    jy2=str(i).replace(u'0',u'0')
    row.append(jy2)
    row.append(u'[[مستخدم:'+user+u'|'+user+u']]')
    for query in query_list:
        if query['name'] in stats:
            jy3=str(stats[query['name']]).replace(u'0',u'0')
            row.append(jy3)
            total += stats[query['name']]
            totals[query['name']] += stats[query['name']]
            totals['total'] += stats[query['name']]
        else:
            row.append(u'0')
    row.append(str(total).replace(u'0',u'0'))
    rows.append('| %s \n|-' % ('\n| '.join(row)))
    i += 1
ttotal=str(totals['total']).replace(u'0',u'0')
output += master_table_template % (
    '\n'.join(['! <span title="%s">%s</span>' % (query['name'], query['short_name']) for query in query_list]), 
    '\n'.join(rows),
    '\n'.join([u'! style="text-align:left;" | %s' % str(totals[query['name']]).replace(u'0',u'0') for query in query_list]) + u'\n! style="text-align:left;" | %s' % ttotal
)

final_output = report_template % (output)
final_output = pagetop+final_output +u'\n'+pagedown
report = wikipedia.Page(site, report_title)
report.put(final_output,message)

cursor.close()
conn.close()