from pathlib import Path
from .match import Match
import json
import csv


class Matches:
    def __init__(self, source, from_list=False, network_type=None):
        self.data = []
        self.names = []
        if from_list:
            for l in source:
                m = Match.read_from_json(l)
                if network_type == None or m.network_type() == network_type:
                    self.data.append(m)
                    self.data[-1].name = Path(l).stem
                    self.names.append(Path(l).stem)
        else:
            for f in Path(source).iterdir():
                if Path(f).suffix == '.json':
                    m = Match.read_from_json(str(f))
                    if network_type == None or m.network_type() == network_type:
                        self.data.append(m)
                        self.data[-1].name = Path(f).stem
                        self.names.append(Path(f).stem)

    @staticmethod
    def from_profile(pname, ppos='profile.csv'):
        source = []
        with open(ppos, 'r', encoding='utf-8') as f:
            for row in csv.reader(f):
                if pname in row:
                    source.append(row[0])
        return Matches(source, True)

    @staticmethod
    def from_profile_expr(expr, ppos='profile.csv'):
        source = []
        with open(ppos, 'r', encoding='utf-8') as f:
            for row in csv.reader(f):
                if expr(row):
                    source.append(row[0])
        return Matches(source, True)
