__author__ = 'kaceymiriholston'

import psycopg2

from config.settings import *
from settings import *
from util.log import log

import util
import reports

def replication():
    db = util.db.connect()
    cur = db.cursor()
    cur.execute("""SELECT
    client_addr,
    sent_offset - (
        replay_offset - (sent_xlog - replay_xlog) * 255 * 16 ^ 6 ) AS byte_lag
    FROM (
        SELECT
            client_addr,
            ('x' || lpad(split_part(sent_location,   '/', 1), 8, '0'))::bit(32)::bigint AS sent_xlog,
            ('x' || lpad(split_part(replay_location, '/', 1), 8, '0'))::bit(32)::bigint AS replay_xlog,
            ('x' || lpad(split_part(sent_location,   '/', 2), 8, '0'))::bit(32)::bigint AS sent_offset,
            ('x' || lpad(split_part(replay_location, '/', 2), 8, '0'))::bit(32)::bigint AS replay_offset
        FROM server.current_pg_stat_replication
    ) AS s;""")
    if cur.rowcount > 0:
        reports.text_report(cur, REPORT_DIR_PATH + '/replication.csv')
    else:
        no_file = REPORT_DIR_PATH + '/swap_usage.txt'
        with open(no_file, 'w') as no_results:
            no_results.write("No results.")
        no_results.close()
        log('No connections recorded; skipping swap_usage report')
        return