#!/usr/bin/python

from __future__ import print_function
import sys
import csv


context = "loadtest"
agent_group_id = "3"
start_number = "2350"
end_number = "2399"
host = "192.168.226.15"

input_csv = sys.argv[1]


def read_csv(filename):
    csv_data = []
    with open(filename) as csvfile:
        csv_file = csv.DictReader(csvfile)
        for row in csv_file:
            csv_data.append(row)

    return csv_data


users = read_csv(input_csv)

for user in users:
    print("INSERT INTO agentfeatures "
          "VALUES "
              "(default,"
              + agent_group_id + ","
              + "'" + user['firstname'] + "',"
              + "'" + user['lastname'] + "',"
              + user['exten'] + ","
              "'',"
              + "'" + user['context'] + "',"
              "'',"
              "0,"
              "'',"
              "'',"
              "'');")

print("\n"
        "SELECT * FROM userfeatures WHERE loginclient BETWEEN '" + start_number + "' AND '" + end_number + "';")

print("\n"
          "UPDATE userfeatures \n"
          "SET agentid = agentfeatures.id \n"
          "FROM agentfeatures \n"
          "WHERE agentfeatures.number = userfeatures.loginclient \n"
          "AND agentfeatures.context = '" + context + "'\n"
          "AND agentfeatures.number BETWEEN '" + start_number + "' AND '" + end_number + "';")

print("\n"
        "SELECT userfeatures.firstname, userfeatures.lastname, usersip.context, usersip.host, linefeatures.number \n"
        "FROM linefeatures \n"
        "LEFT JOIN user_line ON user_line.line_id = linefeatures.id \n"
        "LEFT JOIN userfeatures ON user_line.user_id = userfeatures.id \n"
        "LEFT JOIN usersip ON linefeatures.protocolid = usersip.id AND usersip.category = 'user' AND linefeatures.protocol = usersip.protocol \n"
        "WHERE linefeatures.number BETWEEN '" + start_number + "' AND '" + end_number + "' \n"
        "AND usersip.context = '" + context + "' \n"
        "ORDER BY linefeatures.number ASC;")

print("\n"
        "UPDATE usersip \n"
        "SET host='" + host + "' \n"
        "FROM linefeatures \n"
        "LEFT JOIN user_line ON user_line.line_id = linefeatures.id \n"
        "LEFT JOIN userfeatures ON user_line.user_id = userfeatures.id \n"
        "WHERE linefeatures.protocolid = usersip.id AND usersip.category = 'user' AND linefeatures.protocol = usersip.protocol \n"
        "AND linefeatures.number BETWEEN '" + start_number + "' AND '" + end_number + "' \n"
        "AND usersip.context = '" + context + "';")
