'''
Copyright (c) 2024 Mike Christie
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import urllib.parse
import re
import datetime
import pywikibot
import pymysql
import sys
from dateutil.parser import parse

class FAC_editor:

    def __init__(self, editor, config):
        self.editor = editor
        database = "s55175__ganfilter"
        conn = pymysql.connections.Connection(user=config['client']['user'], password=config['client']['password'], database="s55175__ganfilter", host='tools.db.svc.eqiad.wmflabs')

        cursor = conn.cursor(pymysql.cursors.DictCursor)

        sql = "select nominator from facnom fn where nominator = '" + self.editor.replace("'","''") + "'"
        self.nominations = 0
        try:
            self.nominations = cursor.execute(sql)
        except pymysql.Error as e:
            pass

        sql = "select reviewer from review r where reviewer = '" + self.editor.replace("'","''") + "'"
        self.reviews = 0
        try:
            self.reviews = cursor.execute(sql)
        except pymysql.Error as e:
            pass

        self.reviews_per_nomination = 'Infinite'
        if self.nominations != 0:
            self.reviews_per_nomination = self.reviews/self.nominations

        sql = "select year(f.outcome_date) as fyear, count(*) as noms, sum(case when f.outcome = 'P' then 1 else 0 end) as pctr,"
        sql +=" sum(case when f.outcome = 'A' then 1 else 0 end) as actr, sum(case when f.num_Nominators > 1 then 1 else 0 end) as conomctr "
        sql += " from facnom fn inner join fac f on fn.title collate utf8mb4_bin = f.title collate utf8mb4_bin "
        sql += " and fn.archive_Number = f.archive_Number where fn.nominator = '" + self.editor.replace("'","''") + "' group by year(f.outcome_date)"
        self.nom_details = []
        try:
            row_count = cursor.execute(sql)
            self.nom_details = cursor.fetchall()
        except pymysql.Error as e:
            pass

        sql = "select count(*) as noms, sum(case when f.outcome = 'P' then 1 else 0 end) as pctr,"
        sql +=" sum(case when f.outcome = 'A' then 1 else 0 end) as actr, sum(case when f.num_Nominators > 1 then 1 else 0 end) as conomctr "
        sql += " from facnom fn inner join fac f on fn.title collate utf8mb4_bin = f.title collate utf8mb4_bin "
        sql += " and fn.archive_Number = f.archive_Number where fn.nominator = '" + self.editor.replace("'","''") + "'"
        self.nom_details_totals = []
        try:
            row_count = cursor.execute(sql)
            self.nom_details_totals = cursor.fetchall()[0]
        except pymysql.Error as e:
            pass

        self.review_counts = {'Content': 0, 'Image': 0, 'Source': 0, 'Accessibility': 0}
        sql = "select case when review_type = '' then 'Content' when review_type = 'S' then 'Source' when review_type = 'I' "
        sql += "then 'Image' when review_type = 'A' then 'Accessibility' end as review_type, count(*) as num_reviews from review r where "
        sql += "reviewer = '" + self.editor.replace("'","''") + "' group by case when review_type = '' then 'Content' when review_type = 'S' then 'Source' when "
        sql += "review_type = 'I' then 'Image' when review_type = 'A' then 'Accessibility' end"
        try:
            row_count = cursor.execute(sql)
            for row in cursor.fetchall():
                self.review_counts[row['review_type']] = row['num_reviews']
        except pymysql.Error as e:
            pass
    
        sql = "select year(f.outcome_Date) as fy, count(*) as reviews, sum(case when r.declaration = '' then 1 else 0 end) as no_dec, "
        sql += " sum(case when r.declaration = 'S' then 1 else 0 end) as supports, sum(case when r.declaration = 'OS' then 1 else 0 end) as oppose_to_support, "
        sql += " sum(case when r.declaration = 'SO' then 1 else 0 end) as struck_opposes, sum(case when r.declaration = 'SS' then 1 else 0 end) as struck_supports, "
        sql += " sum(case when r.declaration = 'O' then 1 else 0 end) as opposes, "
        sql += " case when (sum(case when r.declaration = 'O' then 1 else 0 end) + sum(case when r.declaration = 'S' then 1 else 0 end) "
        sql += " + sum(case when r.declaration = 'OS' then 1 else 0 end)) = 0 then 'N/A' else sum(case when r.declaration = 'O' then 1 else 0 end)"
        sql += "/(sum(case when r.declaration = 'O' then 1 else 0 end) + sum(case when r.declaration = 'S' then 1 else 0 end) + sum(case when "
        sql += "r.declaration = 'OS' then 1 else 0 end)) end as oppose_ratio from fac f inner join review r on f.title collate utf8mb4_bin "
        sql += "= r.title collate utf8mb4_bin and f.archive_Number = cast(r.archive_Number as int) where r.reviewer = '" + self.editor.replace("'","''") + "' "
        sql += "group by year(f.outcome_Date) "
        self.review_details = []
        try:
            row_count = cursor.execute(sql)
            self.review_details = cursor.fetchall()
        except pymysql.Error as e:
            pass

        sql = "select count(*) as reviews, sum(case when r.declaration = '' then 1 else 0 end) as no_dec, "
        sql += " sum(case when r.declaration = 'S' then 1 else 0 end) as supports, sum(case when r.declaration = 'OS' then 1 else 0 end) as oppose_to_support, "
        sql += " sum(case when r.declaration = 'SO' then 1 else 0 end) as struck_opposes, sum(case when r.declaration = 'SS' then 1 else 0 end) as struck_supports, "
        sql += " sum(case when r.declaration = 'O' then 1 else 0 end) as opposes, "
        sql += " case when (sum(case when r.declaration = 'O' then 1 else 0 end) + sum(case when r.declaration = 'S' then 1 else 0 end) "
        sql += " + sum(case when r.declaration = 'OS' then 1 else 0 end)) = 0 then 'N/A' else sum(case when r.declaration = 'O' then 1 else 0 end)"
        sql += "/(sum(case when r.declaration = 'O' then 1 else 0 end) + sum(case when r.declaration = 'S' then 1 else 0 end) + sum(case when "
        sql += "r.declaration = 'OS' then 1 else 0 end)) end as oppose_ratio from fac f inner join review r on f.title collate utf8mb4_bin "
        sql += "= r.title collate utf8mb4_bin and f.archive_Number = cast(r.archive_Number as int) where r.reviewer = '" + self.editor.replace("'","''") + "'"
        self.review_details_totals = []
        try:
            row_count = cursor.execute(sql)
            self.review_details_totals = cursor.fetchall()[0]
        except pymysql.Error as e:
            pass

        sql = "select year(f.outcome_date) as fyear, count(*) as reviews, sum(case when r.review_type = '' then 1 else 0 end) as content, "
        sql += "sum(case when r.review_type = 'S' then 1 else 0 end) as source, sum(case when r.review_type = 'I' then 1 else 0 end) as image, "
        sql += "sum(case when r.review_type = 'A' then 1 else 0 end) as accessibility  from fac f inner join review r on f.title collate utf8mb4_bin "
        sql += " = r.title collate utf8mb4_bin and f.archive_Number = cast(r.archive_Number as int) where r.reviewer = '" + self.editor.replace("'","''") + "'"
        sql += " group by year(f.outcome_date)"
        self.review_types = []
        try:
            row_count = cursor.execute(sql)
            self.review_types = cursor.fetchall()
        except pymysql.Error as e:
            pass

        sql = "select count(*) as reviews, sum(case when r.review_type = '' then 1 else 0 end) as content, "
        sql += "sum(case when r.review_type = 'S' then 1 else 0 end) as source, sum(case when r.review_type = 'I' then 1 else 0 end) as image, "
        sql += "sum(case when r.review_type = 'A' then 1 else 0 end) as accessibility  from fac f inner join review r on f.title collate utf8mb4_bin "
        sql += " = r.title collate utf8mb4_bin and f.archive_Number = cast(r.archive_Number as int) where r.reviewer = '" + self.editor.replace("'","''") + "'"
        self.review_types_totals = []
        try:
            row_count = cursor.execute(sql)
            self.review_types_totals = cursor.fetchall()[0]
        except pymysql.Error as e:
            pass

        sql = "select f.title, case when f.archive_number = 99 then 'N/A' else f.archive_number end as archive_number, "
        sql += "case when f.archive_number = 99 then '' else concat('\/archive',f.archive_number) end as archive_string, f.nom_date, "
        sql += "f.outcome, f.outcome_date, datediff(f.outcome_date,f.nom_date) as duration from facnom fn inner join fac f "
        sql += "  on fn.title collate utf8mb4_bin = f.title collate utf8mb4_bin and fn.archive_number = f.archive_number "
        sql += " where fn.nominator = '" + self.editor.replace("'","''") + "' order by f.outcome_date"
        self.nominations_list = []
        try:
            row_count = cursor.execute(sql)
            for row in cursor.fetchall():
                row['title_link'] = row['title'].replace(' ','_')
                self.nominations_list.append(row)
        except pymysql.Error as e:
            pass

        sql = " select f.title, case when f.archive_number = 99 then 'N/A' else f.archive_number end as archive_number, "
        sql += "case when f.archive_number = 99 then '' else concat('\/archive',f.archive_number) end as archive_string, "
        sql += "f.outcome, f.outcome_date, r.review_type, r.declaration from fac f inner join review r on f.title collate "
        sql += "utf8mb4_bin = r.title collate utf8mb4_bin and f.archive_number = cast(r.archive_number as int) where r.reviewer = '" + self.editor.replace("'","''") + "' "
        sql += " order by f.outcome_date"
        self.reviews_list = []
        try:
            row_count = cursor.execute(sql)
            for row in cursor.fetchall():
                row['title_link'] = row['title'].replace(' ','_')
                self.reviews_list.append(row)
        except pymysql.Error as e:
            pass