from datetime import datetime
from peewee import *
from pymrf4.db import db



class BaseModel(Model):
    class Meta:
        database = db


class Torrent(BaseModel):
    info_hash = CharField(unique=True)
    size = BigIntegerField(default=0)
    name = CharField(null=True)
    site = CharField()
    # tracker = CharField()
    total_upload = BigIntegerField(default=0)
    total_download = BigIntegerField(default=0)
    total_upload_actual = BigIntegerField(default=0)

    session_upload = BigIntegerField(default=0)
    session_download = BigIntegerField(default=0)
    session_upload_actual = BigIntegerField(default=0)

    completed = BooleanField(default=False)
    is_seeding = BooleanField(default=False)

    peers = IntegerField(default=0)
    leechers = IntegerField(default=0)
    seeders = IntegerField(default=0)

    last_started_at = DateTimeField(null=True)
    last_announced_at = DateTimeField(null=True)

    last_event = CharField(null=True)

    is_modifying = BooleanField(default=False)

    is_folded = BooleanField(default=False)

    def share_ratio(self):
        # find latest session announce
        download = self.total_download + self.session_download
        return round((self.total_upload_actual + self.session_upload_actual) /
             download if download > 0 else 0, 2)


    def elapsed_since_last_announce(self):
        if self.last_announced_at is None:
            return 1
        return max(1, (datetime.now() - self.last_announced_at).total_seconds())

    def last_announce(self):
        return self.announces.order_by(Announce.created_at).last()


class Announce(BaseModel):
    torrent = ForeignKeyField(Torrent, backref='announces')

    event = CharField(null=True)

    download = BigIntegerField(default=0)
    upload = BigIntegerField(default=0)
    upload_delta = BigIntegerField(default=0)
    upload_actual = BigIntegerField(default=0)
    upload_speed = BigIntegerField(default=0)
    is_modifiying = BooleanField(default=False)
    elapsed_since_last_announce = IntegerField(default=1)
    created_at = DateTimeField(default=datetime.now)
    leechers = IntegerField(default=0)


def create_tables():
    with db:
        db.create_tables([Torrent, Announce])
