import csv
import statistics

from apps.general import headers
import pandas as pd

from data_types import Purchase


def load_csv():
    csv_file = 'SacramentoRealEstateTransactions2008.csv'
    csv_data = pd.read_csv(csv_file)
    return pd.DataFrame(csv_data, columns=['beds', 'baths', 'price', 'city'])


def get_minimum_row(real_estate_data, col):
    return real_estate_data[
        real_estate_data[col] == min(real_estate_data[col])
        ]


def get_maximum_row(real_estate_data, col):
    return real_estate_data[
        real_estate_data[col] == max(real_estate_data[col])
        ]

def get_average(real_estate_data, col=None, value=None):
    if col is None:
        return real_estate_data.mean()
    else:
        data = real_estate_data[real_estate_data[col] == value]
        return data.mean()


def main():
    headers.print_header('Real estate analyser')

    real_estate_data = load_csv()

    print('Header: {}'.format(', '.join(c for c in real_estate_data.columns)))

    min_price_row = get_minimum_row(real_estate_data, col='price')
    max_price_row = get_maximum_row(real_estate_data, col='price')

    average_house = get_average(real_estate_data)
    average_2bed_house = get_average(real_estate_data, col='beds', value=2)

    print('The most expensive house is: {}'.format(max_price_row))
    print('The least expensive house is: {}'.format(min_price_row))

    print('The average house is: {}'.format(average_house))
    print('The average 2 bed house: {}'.format(average_2bed_house))


def load_file(filename):
    purchases = []
    with open(filename, 'r', encoding='utf-8') as fin:
        reader = csv.DictReader(fin, delimiter=',')
        for row in reader:
            p = Purchase.create_from_dict(row)
            purchases.append(p)
    print(purchases[0].__dict__)
    return purchases


def query_data(data):
    data.sort(key=lambda p: p.price)

    high_purchase = data[-1]
    print('The most expensive house costs ${:,}, with {} bed and {} baths'
          .format(high_purchase.price, high_purchase.beds, high_purchase.baths))

    low_purchase = data[0]
    print('The least expensive house costs ${:,}, with {} bed and {} baths'
          .format(low_purchase.price, low_purchase.beds, low_purchase.baths))

    ave_purchase = statistics.mean(p.price for p in data)
    ave_beds = statistics.mean(p.beds for p in data)
    ave_baths = statistics.mean(p.baths for p in data)
    print('Average house costs ${:,.2f}, with {:.1f} bed and {:.1f} baths'
          .format(ave_purchase, ave_beds, ave_baths))

    ave_purchase = statistics.mean(p.price for p in data if p.baths == 2)
    ave_beds = statistics.mean(p.beds for p in data if p.baths == 2)
    ave_sq_ft = statistics.mean(p.sq_ft for p in data if p.baths == 2)
    print('Average 2 bed house costs ${:,.2f}, with {:.1f} bed and sq_ft={:.1f}'
          .format(ave_purchase, ave_beds, ave_sq_ft))


def main_other():
    headers.print_header('Real estate analyser')
    filename = 'SacramentoRealEstateTransactions2008.csv'
    real_estate_data = load_file(filename)
    query_data(real_estate_data)


if __name__ == '__main__':
    main_other()
