import os
from dateutil import parser

from datetime import datetime
from light.cache import Cache
from light.constant import Const
from light.model.datarider import Rider
from light.http.context import Context

CONST = Const()


def main():
    domain = os.environ[CONST.ENV_LIGHT_APP_DOMAIN]
    handler = Context(uid='000000000000000000000001', domain=domain, param={})
    os.makedirs('/data/' + domain, exist_ok=True)

    Cache(domain).init()

    last = read_timestamp(domain)
    codes, error = Rider.instance().code.list(handler, {'condition': {'at': last}})
    if error:
        return print(error)

    for code in codes['items']:
        last = write_source(handler, code, last)

    write_timestamp(domain, last)


def read_timestamp(domain):
    last = datetime(1900, 1, 1, 0, 0, 0)

    timestamp_file = '/data/{0}/pull.timestamp'.format(domain)
    if os.path.isfile(timestamp_file):
        timestamp = open(timestamp_file, 'r', encoding='utf8')
        last = parser.parse(timestamp.read())

    return last


def write_timestamp(domain, last):
    timestamp_file = '/data/{0}/pull.timestamp'.format(domain)
    timestamp = open(timestamp_file, 'w', encoding='utf8')
    timestamp.write(str(last))
    timestamp.close()


def write_source(handler, code, last):
    update_at = code['updateAt']
    name = code['name']
    src = code['source']

    if update_at > last:
        last = update_at

    print('Updated :', name)

    folder = '/data/{0}{1}'.format(handler.domain, name)
    os.makedirs(os.path.dirname(folder), exist_ok=True)

    if code['type'] == 'binary':
        handler.params.id = src
        handler.params.data = {'folder': '/data/' + handler.domain, 'name': name[1:]}
        Rider.read_file_from_grid(handler)
        return last

    source = open(folder, 'w', encoding='utf8')
    source.write(src)
    source.close()
    return last


if __name__ == '__main__':
    # os.environ[CONST.ENV_LIGHT_DB_HOST] = '127.0.0.1'
    # os.environ[CONST.ENV_LIGHT_DB_PORT] = '57017'
    # os.environ[CONST.ENV_LIGHT_DB_USER] = 'light'
    # os.environ[CONST.ENV_LIGHT_DB_PASS] = '2e35501c2b7e'
    # os.environ[CONST.ENV_LIGHT_APP_DOMAIN] = 'LightDB'
    main()
