# coding:utf-8
import data_handler.data_rw as data_rw
import sys
import getopt

opts, args = getopt.getopt(sys.argv[1:], "ahsnf:gci:m:t:d")

if len(opts) == len(args) == 0:
    print("-h for help")

def in_opts(opt):
    for op, value in opts:
        if op == opt:
            return True
    return False

def get_opt_value(opt):
    for op, value in opts:
        if op == opt:
            return value
    return ""


for op, value in opts:
    if op == "-h":
        print('-a print all\n'
              '-a -s sort by ip\n'
              '-a -n sort by name\n'
              '-f xx find xx name with same ip\n'
              '-a -g list sockpuppets\n'
              '-c ip infos counts\n'
              '-i $IP search ip \n'
              '-m $USER1 -t $USER2 check two user \n')

    if op == "-a":
        infos = data_rw.get_info()
        if in_opts("-s"):
            infos.sort(key=lambda x:x[1])
        elif in_opts("-n"):
            infos.sort()
        elif in_opts("-g"):
            temp_ip_map = {}
            has_same_ip = []
            for info in infos:
                if info[1] not in temp_ip_map:
                    temp_ip_map[info[1]] = info
                else:
                    if info[1] not in has_same_ip:
                        has_same_ip.append(info[1])

            sockpuppets = [x for x in infos if x[1] in has_same_ip]
            sockpuppets.sort(key=lambda x: x[1])
            temp_old_ip = ""
            for item in sockpuppets:
                if temp_ip_map != item[1]:
                    temp_ip_map = item[1]
                    print("############################################################")
                print("{:16}{:16}{:32}{:16}".format(item[0],
                                                    item[1],
                                                    item[2],
                                                    item[3]))
            break
        print(infos)

    if op == "-f":
        infos = data_rw.get_info()
        name_list = [x for x in infos if x[0] == value]
        # print("this people has ips:")
        # print(name_list)

        name_ips = [ip[1] for ip in name_list]
        sockpuppets = [x for x in infos if x[1] in name_ips]
        print("this people has sockpuppets :")
        print("{:16}{:16}{:32}{:16}".format("name", "ip", "datetime", "tie_id"))
        for item in sockpuppets:
            print("{:16}{:16}{:32}{:16}".format(item[0],
                                                item[1],
                                                item[2],
                                                item[3]))
    if op == "-c":
        infos = data_rw.get_info()
        print("has {} ip infos".format(len(infos)))

    if op == "-i":
        infos = data_rw.get_info()
        name_list = [x for x in infos if value in x[1]]
        name_list.sort(key=lambda x:x[2])
        print("{:16}{:16}{:32}{:16}".format("name", "ip", "datetime", "tie_id"))
        for item in name_list:
            print("{:16}{:16}{:32}{:16}".format(item[0],
                                                item[1],
                                                item[2],
                                                item[3]))

    if op == "-m":
        user1 = value
        user2 = get_opt_value("-t")
        infos = data_rw.get_info()

        user1_infos = [x for x in infos if x[0] in user1]
        user2_infos = [x for x in infos if x[0] in user2]

        all_match = []
        two_match = []

        def get_ips_info(inner_ip, infos):
            result = [x for x in infos if inner_ip in x[1]]
            return result

        
        user1_ip_infos = []

        result = []
        for item in user1_infos:
            inner_ip = item[1].split(".")
            inner_ip = ".".join(inner_ip[1:3])

            if inner_ip not in user1_ip_infos:
                user1_ip_infos.append(inner_ip)

        for inner_ip in user1_ip_infos:
            result.append([
                inner_ip,
                get_ips_info(inner_ip,user1_infos),
                get_ips_info(inner_ip,user2_infos)
            ]
            )
        
        for item in result:
            print("ip {} :".format(item[0]))
            print("{} has {} items ".format(user1, len(item[1])))
            for user1_info in item[1]:
                print(user1_info)

            print("{} has {} items ".format(user2, len(item[2])))
            for user2_info in item[2]:
                print(user2_info)

    if op == "-d":
        infos = data_rw.get_info()
        result = []
        for item in infos:
            if item[1] != "0.0.0.*" and item[1].strip() != "":
                result.append(item)
        
        data_rw.write_infos(result)